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

Perl - how to grep a block of text from a file -

delphi - How to remove all the grips on a coolbar if I have several coolbands? -

javascript - Animating array of divs; only the final element is modified -