gpt4 book ai didi

c++ - 正确读取和写入 std::vector 到文件中

转载 作者:IT老高 更新时间:2023-10-28 23:27:48 30 4
gpt4 key购买 nike

这就是重点。如何写入和读取包含 std::vector 的二进制文件?

我在想这样的事情:

//============ WRITING A VECTOR INTO A FILE ================
const int DIM = 6;
int array[DIM] = {1,2,3,4,5,6};
std::vector<int> myVector(array, array + DIM);
ofstream FILE(Path, ios::out | ofstream::binary);
FILE.write(reinterpret_cast<const char *>(&myVector), sizeof(vector) * 6);
//===========================================================

但我不知道如何读取这个 vector 。因为我认为以下是正确的,但事实并非如此:

ifstream FILE(Path, ios::in | ifstream::binary);
FILE.read(reinterpret_cast<const char *>(&myVector), sizeof(vector) * 6);

那么,如何进行操作呢?

最佳答案

尝试使用 ostream_iterator/ostreambuf_iteratoristream_iterator/istreambuf_iterator 和 STL copy 方法:

#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>

#include <fstream> // looks like we need this too (edit by π)

std::string path("/some/path/here");

const int DIM = 6;
int array[DIM] = {1,2,3,4,5,6};
std::vector<int> myVector(array, array + DIM);
std::vector<int> newVector;

std::ofstream FILE(path, std::ios::out | std::ofstream::binary);
std::copy(myVector.begin(), myVector.end(), std::ostreambuf_iterator<char>(FILE));

std::ifstream INFILE(path, std::ios::in | std::ifstream::binary);
std::istreambuf_iterator iter(INFILE);
std::copy(iter.begin(), iter.end(), std::back_inserter(newVector));

关于c++ - 正确读取和写入 std::vector 到文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12372531/

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