如何将整个流读入std :: vector? [英] How to read entire stream into a std::vector?

查看:166
本文介绍了如何将整个流读入std :: vector?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我阅读了此处的答案,其中显示了如何将整个流读入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_t并将std::string替换为std::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:\ non-svn \ c ++ \ library \ i \ file \ filereader.cpp(62):错误C2440: '':无法转换 'std :: basic_ifstream>'到 'std :: istreambuf_iterator>'1>
与1> [1> _Elem = uint8_t 1>] 1>
没有构造函数可以采用源类型,也不能构造函数重载 分辨率不明确

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:

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

对我有用.

或者,由于Dietmar说这可能有点粗略,因此您可以执行以下操作:

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

这篇关于如何将整个流读入std :: vector?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆