Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typo3/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 为什么';istreambuf_迭代器的高级工作_C++_Iterator_Binaryfiles_Ifstream_Istream Iterator - Fatal编程技术网

C++ 为什么';istreambuf_迭代器的高级工作

C++ 为什么';istreambuf_迭代器的高级工作,c++,iterator,binaryfiles,ifstream,istream-iterator,C++,Iterator,Binaryfiles,Ifstream,Istream Iterator,我读的是关于把一个完整的文件内容读入一个字符向量。而我希望将文件的一部分加载到字符向量中 #include <iostream> #include <fstream> #include <iterator> #include <vector> #include <algorithm> using namespace std; int main(int argc, char *argv[]) { ifstream ifs(ar

我读的是关于把一个完整的文件内容读入一个字符向量。而我希望将文件的一部分加载到字符向量中

#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;
    });
}
返回一个0。请有人解释一下发生了什么事

为什么不在istreambuf_迭代器上进行高级工作


它起作用了。它使迭代器前进。问题在于,
istreambuf_迭代器
是一个输入迭代器,而不是一个前向迭代器,这意味着它是一个单过程迭代器:一旦你推进它,你就再也不能访问以前的状态了。要做您想做的事情,您只需使用计数为4的老式for循环。

istreambuf\u迭代器
basic\u streambuf
读取连续字节。它不支持定位(
basic\u istream::seekg
basic\u istream::tellg

这是因为它是单通道输入迭代器,而不是前向迭代器或随机访问迭代器;它设计为能够处理不支持定位的流(例如管道或TCP套接字)


您可能会在中找到一些有用的解决方案。

如果其他人偶然发现这个问题,并且想要一些替代的简单代码,您可以尝试以下方法:

        std::vector<char> buffer{4};
        std::ifstream source{argv[1], std::ios_base::binary};
        source.read(buffer.data(), buffer.size());
std::向量缓冲区{4};
std::ifstream source{argv[1],std::ios_base::binary};
读取(buffer.data(),buffer.size());

istream\u迭代器
s是输入迭代器,也称为单过程迭代器。仔细阅读,你完全误用了它们。特别是
endItr(begintr)
将导致
endItr
begintr
使用同一个流。@Xeo:你的意思是,一个ifstream不能有两个迭代器,因为输入迭代器的行为是这样的?同一ifstream的两个迭代器共享相同的底层
std::basic\u streambuf
,因此是相同的。end
std::istreambuf_迭代器是默认构造的。此外,
std::distance(begin,end)
通过增加
begin
直到
begin==end
@bit2shift,从而影响基础
std::basic_streambuf
。感谢您的澄清。因此,通过向量的ctor直接将其读入向量是不可能的。但我遇到的问题是多个迭代器,我知道,一旦
endItr
是高级的,它就不能向后移动,但这是否意味着所有迭代器都是相同的?或者像我要求Xeo的那样,一个ifstream在任何时候都只能有一个迭代器(概念上)?@legends2k是的,就是这样。它源于这样一个事实,即流通常是不可查找的(例如,网络流)。我不确定推进
endItr
是否会使
begintr
无效,或者它们是否变得相同,但不管怎样,您尝试的方法都不起作用。我想可能有一个特定的迭代器用于允许多次迭代的文件,但没有:(您还可以编写一个迭代器来包装istreambuf_迭代器并计算前进的次数;这将允许您直接使用向量构造函数。问题是
endItr
begintr
初始化,有效地共享相同的
std::basic_streambuf
对象。
endItr
需要构造默认值以使其成为流结束迭代器。如果有疑问,请始终阅读。
        std::vector<char> buffer{4};
        std::ifstream source{argv[1], std::ios_base::binary};
        source.read(buffer.data(), buffer.size());