gpt4 book ai didi

c++ - 使用一对迭代器初始化字符串

转载 作者:搜寻专家 更新时间:2023-10-31 01:23:17 24 4
gpt4 key购买 nike

我正在尝试使用迭代器初始化字符串,类似这样的方法有效:

ifstream fin("tmp.txt");  
istream_iterator<char> in_i(fin), eos;
//here eos is 1 over the end
string s(in_i, eos);

但这不是:

ifstream fin("tmp.txt");
istream_iterator<char> in_i(fin), eos(fin);
/* here eos is at this same position as in_i*/
//moving eos forward
for (int i = 0; i < 20; ++i)
{
++eos;
}
// trying to initialize string with
// pair of iterators gives me ""
// result
string s(in_i, eos);

谢谢。

最佳答案

我不认为你可以将结束迭代器推进到合适的位置:推进迭代器意味着读取输入,而且两个迭代器都引用同一个流 - 因此推进一个迭代器意味着推进第二个。它们最终都引用了流中的相同位置。

除非您愿意编写或找到一个迭代器适配器(boost?)对某个迭代器引用的 n 项执行操作,否则可能无法像那样初始化字符串。或者您使用其他方法读取值并稍后设置字符串的值。

关于c++ - 使用一对迭代器初始化字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1702929/

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