本文介绍了为什么istreambuf_iterator无法进行工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我正在阅读用istream_iterators构建向量,这是关于读取一个将文件内容完整地转换为chars向量.虽然我希望将文件的一部分加载到chars的向量中.

I was reading Constructing a vector with istream_iterators which is about reading a complete file contents into a vector of chars. While I want a portion of a file to be loaded in to a vector of chars.

#include <iostream>
#include <fstream>
#include <iterator>
#include <vector>
#include <algorithm>

using namespace std;

int main(int argc, char *argv[])
{
    ifstream ifs(argv[1], ios::binary);
    istreambuf_iterator<char> beginItr(ifs);
    istreambuf_iterator<char> endItr(beginItr);
    advance(endItr, 4);
    vector<char> data(beginItr, endItr);
    for_each(data.cbegin(), data.cend(), [](char ch)
    {
            cout << ch << endl;
    });
}

这不起作用,因为前进不起作用,而上述问题的可接受答案有效.为什么高级功能不能在istreambuf_iterator上使用?

This doesn't work, since advance doesn't work, while the aforementioned question's accepted answer works. Why doesn't the advance work on istreambuf_iterator?

  endItr++;
  endItr++;
  endItr++;
  endItr++;
  cout << distance(beginItr, endItr) << endl;

返回0.请有人说明发生了什么!

returns a 0. Please somebody explain what is going on!

推荐答案

有效.它使迭代器前进.问题在于istreambuf_iterator输入迭代器,而不是正向迭代器,这意味着它是单遍迭代器:一旦推进,就永远无法访问再次回到先前的状态.要执行您想要的操作,您只需使用计数为4的老式for循环即可.

It works. It advances the iterator. The problem is that an istreambuf_iterator is an input iterator but not a forward iterator, meaning it is a single pass iterator: once you advance it, you can never access the previous state again. To do what you want you can simply use an old-fashioned for loop that counts to 4.

这篇关于为什么istreambuf_iterator无法进行工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 09:08