请查看此代码段
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是两个不同的迭代器。有人帮我个忙吗?
最佳答案
std::istreambuf_iterator
is a single-pass input iterator that reads successive characters from thestd::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/