我提出了以下示例代碼(與-std編譯= C++ 11)寫入「3D」矢量莢類型爲二進制文件C++
它是填充有編號8到處一個三維矢量10 * 20 * 30 。 我不知道如何將其寫入磁盤並將其讀回。有人能告訴我如何請或完成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();
}
您可以通過每次寫入/讀取* vector向量的每個向量來做到這一點。或者,你可以保留所有這些,從一開始就使用'std :: vector',並自己對所使用的下標數學運算。 –
WhozCraig
常用約定是,如果不修改元素,則應該使用'auto const&'。 –