C++中vector数据持久化有文本、二进制和序列化三种主要方式:1. 文本文件适合基本类型,读写直观;2. 二进制文件高效紧凑,适用于数值类型,需注意大小端问题;3. JSON等序列化库支持复杂结构,跨平台易读,推荐nlohmann/json处理vector<string>或自定义类型。

在C++中,将
vector
如果
vector
int
double
string
<fstream>
#include <fstream>
#include <vector>
#include <iostream>
<p>std::vector<int> data = {1, 2, 3, 4, 5};
std::ofstream file("data.txt");
if (file.is_open()) {
for (const auto& item : data) {
file << item << "\n";
}
file.close();
}
读取时逐行解析即可:
std::vector<int> loaded;
std::ifstream infile("data.txt");
int value;
while (infile >> value) {
loaded.push_back(value);
}
对于
vector<int>
vector<double>
write()
立即学习“C++免费学习笔记(深入)”;
示例:vector<double> 二进制写入std::vector<double> values = {1.1, 2.2, 3.3, 4.4};
std::ofstream file("data.bin", std::ios::binary);
size_t size = values.size();
file.write(reinterpret_cast<const char*>(&size), sizeof(size));
file.write(reinterpret_cast<const char*>(values.data()), values.size() * sizeof(double));
file.close();
读取时按相同格式还原:
std::vector<double> loaded;
std::ifstream infile("data.bin", std::ios::binary);
size_t size;
infile.read(reinterpret_cast<char*>(&size), sizeof(size));
loaded.resize(size);
infile.read(reinterpret_cast<char*>(loaded.data()), size * sizeof(double));
若需跨平台、易读或存储复杂结构(如
vector<Person>
#include <nlohmann/json.hpp>
#include <fstream>
<p>std::vector<std::string> names = {"Alice", "Bob", "Charlie"};
nlohmann::json j = names;</p><p>std::ofstream file("names.json");
file << j.dump(4); // 格式化输出
读取也很简单:
std::ifstream infile("names.json");
nlohmann::json j;
infile >> j;
std::vector<std::string> loaded = j.get<std::vector<std::string>>();
如果
vector
struct Point {
double x, y;
};
<p>// 手动序列化为文本
std::ofstream file("points.txt");
for (const auto& p : points) {
file << p.x << " " << p.y << "\n";
}
或扩展 JSON 方法支持结构体(需定义 to_json/from_json 函数)。
基本上就这些。选择哪种方式取决于你的需求:调试用文本,性能用二进制,通用性用JSON。关键是读写格式要一致,注意字节序和类型对齐问题(尤其在跨平台时)。
以上就是c++++中如何将vector的内容写入文件_vector数据持久化到文件的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号