Why do successive istream_iter objects increment the iterated stream?

不打扰是莪最后的温柔 提交于 2021-01-27 10:40:53

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!