Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
221 views
in Technique[技术] by (71.8m points)

c++ - Distance between istream_iterators

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

std::istream_iterator is an InputIterator, 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) using std::copy without knowing the size beforehand, just use std::back_inserter to append the data being read to the vector.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...