[英]write '3d' vector pod type to binary file c++
我编写了以下示例代码(使用-std = c ++ 11编译)
这是一个3d矢量10 * 20 * 30,到处都是数字8。 我不知道如何将其写入磁盘并读回。 有人可以告诉我如何取悦或完成r-rw例程吗?
#include <iostream>
#include <vector>
#include <fstream>
int main(int argc, char *argv[])
{
//'3d' vector filled with 8's
std::vector<std::vector<std::vector<int>>> all8s (10,std::vector<std::vector<int>>(20,std::vector <int>(30,8)));;
//print the whole
std::cout << "1st size " << all8s.size() << " \n";
for ( auto& elemTop : all8s ) {
std::cout << "2nd size " << elemTop.size() << " \n";
for ( auto& elemMiddle : elemTop ) {
std::cout << "3th size " << elemMiddle.size() << " \n";
for ( auto& elemBottom : elemMiddle ){
std::cout << elemBottom << ",";
}
std::cout << "\n";
}
}
//write binary file
std::ofstream out("all8s.bin", std::ios::out | std::ios::binary);
//how do I write this to disk
out.close();
//read it?
std::vector<std::vector<std::vector<int>>> all8sReloaded;
std::ifstream in("all8s.bin", std::ios::in | std::ios::binary);
//how to read it back?
in.close();
}
不可能将所有块都写在一个写语句中。 根据您的代码,一个非常简单的解决方案是:
for ( auto& elemTop : all8s )
for ( auto& elemMiddle : elemTop )
for ( auto& elemBottom : elemMiddle )
cout.write (reinterpret_cast(const char*)&elemBottom, sizeof(int));
另一方面,如果您想阅读它们,则需要知道向量的维数。 这是相似的。 如果不是,则必须在数据之前保存此大小。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.