> But I do not understand how this method works and why all this parameters are needed.
All the parameters are not needed; except for the first, they have reasonable default values.
And you should be be using the defaults for the traits type and the distance type unless you have created a stream class of your own which uses some different types for these.
#include <iostream>
#include <iterator>
#include <sstream>
int main()
{
{
std::istringstream stm( "0 1 2 3 4 5 6 7 8 9" ) ;
// istream iterator iterating over objects of type int
// use defaults for the remaining three template parameters
std::istream_iterator<int> iter(stm), end ;
for( ; iter != end ; ++iter ) std::cout << *iter << ' ' ;
std::cout << '\n' ;
}
{
// istream iterator iterating over objects of type int
// the character type of the stream is wchar_t
// use defaults for the remaining two template parameters
std::wistringstream stm( L"10 11 12 13 14 15 16 17 18 19" ) ;
std::istream_iterator<int,wchar_t> iter(stm), end ;
for( ; iter != end ; ++iter ) std::wcout << *iter << L' ' ;
std::wcout << L'\n' ;
}
}
The default-constructed std::istream_iterator is known as the end-of-stream iterator. When a valid std::istream_iterator reaches the end of the underlying stream, it becomes equal to the end-of-stream iterator. Dereferencing or incrementing it further invokes undefined behavior.
- http://en.cppreference.com/w/cpp/iterator/istream_iterator
And the answer would become obvious.
In std::istream_iterator<int> iter(stm), end ;
end is an iterator that is default-constructed; it signals end of stream.
To iterate over every element in the sequence, we move the iterator forward till it becomes equal to end. for( ; iter != end ; ++iter ) { /* ... */ }
Once it becomes equal to end, it has gone past the last element in the sequence (here, it is at end-of-stream).