【问题标题】:Advancing multiple iterators into the same stringstream将多个迭代器推进到同一个字符串流中
【发布时间】:2021-01-10 12:12:20
【问题描述】:

请查看此代码 sn-p

  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 是两个不同的迭代器。

有人帮我个忙吗?

【问题讨论】:

  • 你期待什么?
  • 另外,您在代码中的注释暗示您第二次得到“b a”,但您的输出有“b b”,并且缺少您输出的其他字符串。请附上您提供的 sn-p 的真实输出

标签: c++ io stream iterator


【解决方案1】:

来自cppreference

std::istreambuf_iterator 是一个单通道输入迭代器,它从构造它的 std::basic_streambuf 对象中读取连续字符。

这里的重要部分是单次传递特性:一旦读取了一个值,就不能再返回并再次读取它。回想一下,例如,您可以将std::istreambuf_iterator 用于std::cin。如果您在程序中从 std::cin 读取,这意味着您可能会以交互方式输入字符 - 没有回头路(您必须将字节保存在 std::string 或类似的地方才能实现)。

现在,当创建引用相同流对象的多个迭代器时,推进一个意味着读取一个字符 - 所有迭代器都可以看到该字符。这是由于迭代器的单通性质,另请参阅operator* 的文档:

通过调用 sbuf_->sgetc() 读取单个字符,其中 sbuf_ 是存储的指向流缓冲区的指针。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-09-03
    • 1970-01-01
    • 1970-01-01
    • 2021-11-29
    • 2012-09-08
    • 1970-01-01
    • 2019-08-01
    • 2011-06-21
    相关资源
    最近更新 更多