How to read entire stream into a 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_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:
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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何将整个流读入 std::vector?
基础教程推荐
- C++ 程序在执行 std::string 分配时总是崩溃 2022-01-01
- C++,'if' 表达式中的变量声明 2021-01-01
- 如何在 C++ 中处理或避免堆栈溢出 2022-01-01
- 调用std::Package_TASK::Get_Future()时可能出现争用情况 2022-12-17
- 什么是T&&(双与号)在 C++11 中是什么意思? 2022-11-04
- 设计字符串本地化的最佳方法 2022-01-01
- 您如何将 CreateThread 用于属于类成员的函数? 2021-01-01
- 如何定义双括号/双迭代器运算符,类似于向量的向量? 2022-01-01
- 运算符重载的基本规则和习语是什么? 2022-10-31
- C++ 标准:取消引用 NULL 指针以获取引用? 2021-01-01