我读了an answer here显示如何使用以下一(两个)衬里将整个流读入 std::string:
std::istreambuf_iterator<char> eos;
std::string s(std::istreambuf_iterator<char>(stream), eos);
为了做一些类似于将二进制流读入 std::vector
的事情,为什么我不能简单地将 char
替换为 uint8_t
和 std::string
与 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):
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/