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

How to read entire stream into a std::vector?(如何将整个流读入 std::vector?)
本文介绍了如何将整个流读入 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_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);
              });

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

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Rising edge interrupt triggering multiple times on STM32 Nucleo(在STM32 Nucleo上多次触发上升沿中断)
How to use va_list correctly in a sequence of wrapper functions calls?(如何在一系列包装函数调用中正确使用 va_list?)
OpenGL Perspective Projection Clipping Polygon with Vertex Outside Frustum = Wrong texture mapping?(OpenGL透视投影裁剪多边形,顶点在视锥外=错误的纹理映射?)
How does one properly deserialize a byte array back into an object in C++?(如何正确地将字节数组反序列化回 C++ 中的对象?)
What free tiniest flash file system could you advice for embedded system?(您可以为嵌入式系统推荐什么免费的最小闪存文件系统?)
Volatile member variables vs. volatile object?(易失性成员变量与易失性对象?)