I am trying to count the amount of elements read by std::cin
by using std::distance
for the constructor argument of a vector in advance, like so:
// Gives correct amount, but now can't use to put into vector
int size = std::distance(std::istream_iterator<std::string>(std::cin),
std::istream_iterator<std::string>());
std::vector v(size);
// Already read from stream
std::copy(...);
Obviously I can complete this in one step with std::copy
, but that would require setting a size beforehand. My question isn't about vectors though, it's about getting the size of an arbitrary input using std::istream_iterator
without affecting the stream. Any ideas?
std::istream_iterator
is anInputIterator
, which means it only supports a single pass over the range you're iterating. There's no way to figure out the size, and then go back to the beginning to read the data.You can read from
std::cin
(or any other input stream) usingstd::copy
without knowing the size beforehand, just usestd::back_inserter
to append the data being read to thevector
.