c++ - Distance between istream_iterators -


i trying count amount of elements read std::cin using std::distance constructor argument of vector in advance, so:

// gives correct amount, can't use put vector int size = std::distance(std::istream_iterator<std::string>(std::cin),         std::istream_iterator<std::string>());  std::vector v(size);  // read stream std::copy(...); 

obviously can complete in 1 step std::copy, require setting size beforehand. question isn't vectors though, it's getting size of arbitrary input using std::istream_iterator without affecting stream. ideas?

std::istream_iterator inputiterator, means supports single pass on range you're iterating. there's no way figure out size, , go beginning read data.

you can read std::cin (or other input stream) using std::copy without knowing size beforehand, use std::back_inserter append data being read vector.

std::vector v; std::copy( std::istream_iterator<std::string>(std::cin),             std::istream_iterator<std::string>(),            std::back_inserter(v) ); 

Comments

Popular posts from this blog

c++ - Function signature as a function template parameter -

algorithm - What are some ways to combine a number of (potentially incompatible) sorted sub-sets of a total set into a (partial) ordering of the total set? -

How to call a javascript function after the page loads with a chrome extension? -