I saw a piece of C++ code to count the number of words inputted from standard input:
#include <iostream>
#include <iterator>
#include <string>
using namespace std;
int main() {
auto ss {
istream_iterator<string>{cin}
};
cout << distance(ss, {}) << endl;
return 0;
}
I have several questions:
- What's the type of
auto ss? - What does
distance(ss, {})do? Why does it calculate the number of words?
My guess is:
istream_iterator<string>{cin}converts the standard input into theistream_iteratortype, automatically separated by space (why?). Thussslooks like acontainerwith all words as its elements;distance(ss, {})calculates the distance between the 1st element and the empty (thus outside of the last, but why?) element.
Can someone help me to go through my guess on this fantastic short piece of code?
auto ssdeducesssto bestd::istream_iterator<std::string>, because that is what the full statement is constructing and assigning toss.istream_iteratoruses the specifiedistream'soperator>>to read formatted input of the specified type, whereoperator>>reads input delimited by whitespace, including space characters, line breaks, etc. So, in this case,istream_iterator<string>is readingstd::stringvalues fromstd::cinone whitespace-delimited word at a time.istream_iteratoris an input iterator, and a default-constructedistream_iteratordenotes an end-of-stream iterator. Whenistream_iteratorstops reading (EOF is reached, bad input is entered, etc), its value becomes equal to the end-of-stream iterator.std::distance()returns the number of elements in a range denoted by a pair of iterators. For a non-random input iterator, likeistream_iterator,std::distance()iterates the range one element at a time via the iterator'soperator++, counting the number of times it incremented the iterator, until the target iterator is reached. So, in this case,istream_iterator::operator++internally reads a value from itsistream, thusstd::distance()effectively returns how many words are successfully read fromstd::cinuntil end-of-stream is reached.So, the code you have shown is roughly just an algorithmic way of writing the following equivalent loop: