使用fstream将vector写入文件,可选择文本或二进制方式。文本方式便于查看,如用ofstream逐个写入int或string元素;二进制方式高效,适用于POD类型,需用write()写入data()指针。
在C++中,将vector的内容写入文件是一个常见的需求,比如保存程序运行结果或持久化数据。最常用的方法是使用标准库中的头文件提供的文件流操作。
包含必要的头文件
要进行文件操作,需要包含和:
#include
#include iostream>
将vector写入文本文件
如果vector中存储的是基本类型(如int、double、string等),可以逐个元素写入文本文件,便于查看和调试。
示例:将vector写入文本文件
std:
:ofstream file("data.txt");if (file.is_open()) {
for (const auto& item : data) {
file }
file.close();
} else {
std::cerr }
上述代码将每个数字写在单独一行。你也可以用空格分隔:file
处理字符串vector
对于vector<:string>,方法类似:
std::ofstream file("words.txt");
if (file.is_open()) {
for (const auto& word : words) {
file }
file.close();
}
以二进制方式写入vector
若追求效率或数据保密性,可将vector以二进制形式写入文件。适用于数值类型数组。
注意:仅适用于POD(Plain Old Data)类型,如int、double等。
std::ofstream file("values.bin", std::ios::binary);
if (file.is_open()) {
file.write(reinterpret_cast
values.size() * sizeof(double));
file.close();
}
读取时需使用std::ifstream配合read()函数,并确保类型一致。
基本上就这些。根据需求选择文本或二进制方式,注意检查文件是否成功打开,避免静默失败。








