Syn*_*ter 0 c++ file-io vector
我有一个矢量,其大小可能非常大(100万个元素).我将向量的内容写为文件作为字节值.我无法弄清楚如何将字节值读回到向量中.
这是代码:
#include <fstream>
#include <vector>
#include <iterator>
#include <iostream>
using namespace std;
int main()
{
// Filling a vector with values
std::vector<bool> ve;
ve.push_back(true);
ve.push_back(false);
ve.push_back(true);
ve.push_back(false);
ve.push_back(true);
// Printing the values of the vector
for(unsigned int i = 0; i < ve.size(); i++)
cout << ve.at(i) << ".";
cout << endl;
// Writing the vector contents to a file
const char* file_name = "abc.txt";
ofstream outfile(file_name, ios::out | ios::binary);
outfile.write((const char*)&(ve[0]), ve.size());
outfile.close();
// Reading the file and filling the vector with values
ifstream infile ("abc.txt", ifstream::binary);
vector<bool> out_ve((std::istreambuf_iterator<char>(infile)),
std::istreambuf_iterator<char>());
while( !infile.eof() )
out_ve.push_back(infile.get());
// Checking if the values read are the same as the original values
cout << "SIZE: " << out_ve.size() << endl;
for(unsigned int i = 0; i < out_ve.size(); i++)
cout << out_ve.at(i) << ".";
cout << endl;
infile.close();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
[edit]写入后关闭文件,输出与输入非常不同.
1.0.1.0.1.
SIZE: 6
1.1.1.0.1.1.
Run Code Online (Sandbox Code Playgroud)
如何将正确的元素输入向量out_ve?
从大多数STL容器中写入数据是无法完成的,outfile.write((const char*)&(ve[0]), ve.size());
因为它们以复杂的方式管理其内存,这是它们运行方式的基础.因为vector
它可以工作,因为内存存储是连续的,但vector<bool>
由于它将多个bool打包成一个字节的方式,因此是特殊的.正如评论者已经指出的那样,ve[0]
返回一个特殊的临时准引用类型,并通过转换将该引用写出来char*
将产生与向量中的数据完全无关的东西.
即使这种结构允许您访问向量的原始内存,您用于写出数据的代码也与您用于读取数据的代码不兼容.您用来写出数据的代码会将 8 bool
个条目分别包含在每个char
代码中,但您用于读取数据的代码会将每个代码转换char
为单个代码bool
.
由于您使用a读回数据istreambuf_iterator
,为什么不以相同的方式写出来:
std::copy(ve.begin(), ve.end(), std::ostreambuf_iterator<char>(outfile));
Run Code Online (Sandbox Code Playgroud)
这写出bool
每个字节一个.
如果你想在每个写入一位的压缩表示中写出数据bool
,我认为你需要发明自己的输入和输出迭代器.