gpt4 book ai didi

c++ - 对 'std::istreambuf_iterator' 的用法感到困惑

转载 作者:可可西里 更新时间:2023-11-01 15:40:04 27 4
gpt4 key购买 nike

以下是an example from cppreference.com ,

The Code is:
#include <vector>
#include <sstream>
#include <iostream>
#include <iterator>

int main()
{
// typical use case: an input stream represented as a pair of iterators
std::istringstream in("Hello, world");
std::vector<char> v( (std::istreambuf_iterator<char>(in)),
std::istreambuf_iterator<char>() );
std::cout << "v has " << v.size() << " bytes. ";
v.push_back('\0');
std::cout << "it holds \"" << &v[0] << "\"\n";


// demonstration of the single-pass nature
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';

}

我有两个问题:

  1. 有人可以详细说明代码 std::vector<char> v( (std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>() ); , 我不太明白它在做什么..为什么我们可以通过使用 cout<<&v[0] 来打印字符串“Hello, world”
  2. 为什么 *i2 的实际值会从“a”跳到“c”?有人可以解释它的机制吗?

非常感谢!

最佳答案

Can someone elaborate on the code ...

std::vector<T>有一个构造函数在 <T> 上接受两个迭代器- 一个用于范围的开始,一个用于范围的结束。

此构造函数从输入流生成输入流迭代器 in :

std::istreambuf_iterator<char>(in)

您可以继续访问其元素,直到到达流的末尾。一旦到达流的末尾,迭代器就等同于使用默认构造函数创建的迭代器:

std::istreambuf_iterator<char>()

因此,传递这对迭代器构造一个vector<T>来自从输入流读取的数据。整个流将被消耗。

Why does the apprent value of *i2 jump for "a" to "c"?

两个迭代器都从同一个流中读取。当您增加第一个迭代器时,它会消耗 'b'来自底层流。与此同时,i2指的是流的第一个字符,它在构建时没有前进就得到了。

一旦你递增i2 , 它向流询问下一个字符。字符'b'已经被消费了,所以下一个字符是'c' .

最后,该代码使用了一个您可能忽略的小技巧:它将空终止符插入 vector<char> 中。为了能够使用 const char* 打印 vector 过载 operator <<(...) .

关于c++ - 对 'std::istreambuf_iterator' 的用法感到困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27406789/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com