gpt4 book ai didi

c++ - 将 '3d' vector Pod 类型写入二进制文件 C++

转载 作者:行者123 更新时间:2023-11-30 03:39:45 25 4
gpt4 key购买 nike

我做了下面的示例代码(用-std=c++11编译)

这是一个 10*20*30 的 3d vector ,到处都是数字 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();
}

最佳答案

不可能在一个写语句中写完所有的 block 。根据您的代码,一个非常简单的解决方案是:

for ( auto& elemTop : all8s )
for ( auto& elemMiddle : elemTop )
for ( auto& elemBottom : elemMiddle )
cout.write (reinterpret_cast(const char*)&elemBottom, sizeof(int));

另一方面,如果您想阅读它们,则需要知道 vector 的维度;它是相似的。否则,您必须在数据之前保存此尺寸。

关于c++ - 将 '3d' vector Pod 类型写入二进制文件 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38575346/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com