问题
Why does the following code output c
?
// main.cpp
#include <iostream>
#include <sstream>
#include <iterator>
int main( int argc, char* argv[] )
{
std::string p( "abcdefghijklmnopqrstuvwxyz" );
std::stringstream ss(p);
std::istream_iterator<char> i( ss );
std::istream_iterator<char> j( ss );
std::istream_iterator<char> k( ss );
std::cout << *k << std::endl;
return 0;
}
.
$ g++ --version
g++ (GCC) 9.2.1 20190827 (Red Hat 9.2.1-1)
Copyright (C) 2019 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
$ g++ -g ./main.cpp && ./a.out
c
It's sort of like each successive istream_iterator
instance is implicitly iterating "something internal" to the stringstream
. Why doesn't each istream_iterator
instance start at the start of its istream_type
?
回答1:
Yes, the constructor of istream_iterator performs reading, and i
, j
, k
use the same stream so they're interactive.
(emphasis mine)
3) Initializes the iterator, stores the address of stream in a data member, and performs the first read from the input stream to initialize the cached value data member.
来源:https://stackoverflow.com/questions/61356433/why-do-successive-istream-iter-objects-increment-the-iterated-stream