c++ - 将多个迭代器推进到同一字符串流

标签 c++ io stream iterator

请查看此代码段

  std::istringstream s("abc");
  std::istreambuf_iterator<char> i1(s), i2(s);
  std::cout<< "i1 returns "<<*i1<<'\n'
           << "i2 returns "<<*i2<<'\n';
  ++i1;
  std::cout<<"after incrementing i1, but not i2\n"
           <<"i1 returns "<<*i1<<'\n'
           <<"i2 returns "<<*i2<<'\n';
  ++i2; // this makes the apparent value of *i2 to jump from 'a' to 'c'
  std::cout << "after incrementing i2, but not i1\n"
            << "i1 returns " << *i1 << '\n'
            << "i2 returns " << *i2 << '\n';
我得到的输出像
a
a

b
b

c
c
这与我的预期完全不同,因为i1和i2是两个不同的迭代器。
有人帮我个忙吗?

最佳答案

cppreference:

std::istreambuf_iterator is a single-pass input iterator that reads successive characters from the std::basic_streambuf object for which it was constructed.


这里的重要部分是单遍特性:一旦读取了值,就无法返回并再次读取它。回想一下,您可以将std::istreambuf_iterator用作std::cin。如果您从程序中的std::cin中读取内容,则意味着您可以以交互方式键入字符-不能返回(必须将字节保存在std::string中或类似的字符中才能实现)。
现在,当创建引用相同流对象的多个迭代器时,前进一个意味着读取一个字符-所有迭代器都可以看到该字符。这是由于迭代器的单遍性质,另请参见operator*的文档:

Reads a single character by calling sbuf_->sgetc() where sbuf_ is the stored pointer to the stream buffer.


显然,所有迭代器实例都共享解引用运算符使用的状态。

关于c++ - 将多个迭代器推进到同一字符串流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64042418/

相关文章:

c++ - 重定向 C++ fstream

c++ - 如何制作一个不刷新 std::cout 的简单 C++ 程序

C++ 加载文件

C++,在for()函数内将复数与普通 double 组合时出错

c++ - 对应该在 C++ 中保存结构的缓冲区使用右对齐

c - 如何检查 fwrite() 在 C 中是否有效?

c++ - 为什么流运算符在 C++ 中返回引用?

c++ - 英特尔引脚 : Instrumentate running process

file - 如何在文件开头添加一行?

java - 如何在不关闭线程的情况下中断被某些套接字 IO 操作阻塞的线程