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

2022-01-07 00:00:00 stream vector c++ stl ifstream

我阅读了此处的答案,展示了如何使用以下内容将整个流读入 std::string (二)班轮:

I read an answer here showing how to read an entire stream into a std::string with the following one (two) liner:

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

对于将二进制流读入 std::vector 的类似操作,为什么我不能简单地将 char 替换为 uint8_tstd::stringstd::vector?

For doing something similar to read a binary stream into a std::vector, why can't I simply replace char with uint8_t and std::string with std::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):

The above produces a compiler error (VC2013):

1>d: on-svnc++libraryifilefilereader.cpp(62):错误 C2440:'' : 不能从'std::basic_ifstream>' 到'std::istreambuf_iterator>' 1>
与 1> [ 1> _Elem=uint8_t 1> ] 1>
没有构造函数可以采用源类型或构造函数重载分辨率不明确

1>d: on-svnc++libraryifilefilereader.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:

There's just a type mismatch. ifstream is just a typedef:

typedef basic_ifstream<char> ifstream;

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

So if you want to use a different underlying type, you just have to tell it:

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);

这对我有用.

或者,因为迪特玛说这可能有点粗略,你可以这样做:

Or, since Dietmar says this might be a little sketchy, you could do something like:

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);
              });

相关文章