c++ - 如何将整个流读入 std::vector?

标签 c++ vector stl stream ifstream

我读了an answer here显示如何使用以下一(两个)衬里将整个流读入 std::string:

std::istreambuf_iterator<char> eos;    
std::string s(std::istreambuf_iterator<char>(stream), eos);

为了做一些类似于将二进制流读入 std::vector 的事情,为什么我不能简单地将 char 替换为 uint8_tstd::stringstd::vector?

auto stream = std::ifstream(path, std::ios::in | std::ios::binary);    
auto eos = std::istreambuf_iterator<uint8_t>();
auto buffer = std::vector<uint8_t>(std::istreambuf_iterator<uint8_t>(stream), eos);

以上会产生编译错误(VC2013):

1>d:\non-svn\c++\library\i\file\filereader.cpp(62): error C2440: '' : cannot convert from 'std::basic_ifstream>' to 'std::istreambuf_iterator>' 1>
with 1> [ 1> _Elem=uint8_t 1> ] 1>
No constructor could take the source type, or constructor overload resolution was ambiguous

最佳答案

只是类型不匹配。 ifstream 只是一个类型定义:

typedef basic_ifstream<char> ifstream;

所以如果你想使用不同的底层类型,你只需要告诉它:

std::basic_ifstream<uint8_t> stream(path, std::ios::in | std::ios::binary);    
auto eos = std::istreambuf_iterator<uint8_t>();
auto buffer = std::vector<uint8_t>(std::istreambuf_iterator<uint8_t>(stream), eos);

这对我有用。

或者,由于 Dietmar 说这可能有点粗略,您可以这样做:

auto stream = std::ifstream(...);
std::vector<uint8_t> data;

std::for_each(std::istreambuf_iterator<char>(stream),
              std::istreambuf_iterator<char>(),
              [&data](const char c){
                  data.push_back(c);
              });

关于c++ - 如何将整个流读入 std::vector?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26589317/

相关文章:

c++ - unordered_map 中迭代器的效率 (C++)

c++ - 访问各种类型的可变参数模板

c++ - 关于c++ vector中for_each的一个问题

java - Vector 是一个过时的集合

c++ - 使用 auto 推导的 lambda 成员函数模板

c++ - Linux下如何压缩图片?

c++ - 为什么我收到错误 : 'No match for operator >> in std' ?

c++ - std::vector 持有基类实例而不是派生类的实例

c++ - 为标准 C++ 类型定义 NULL/Empty 值

c++ - 如何在 C++ 中处理堆