如何将矢量值写入文件

Tim*_*der 21 c++ vector

我有一个大矢量.

我使用的方式大大增加了程序的运行时间.第一种是在使用字符串时将所有值stringstreams写入字符串,然后将字符串写入文件.另一种方法是在事实之后创建一个长字符串并将其写入文件.但是,这两者都很慢.

有没有办法只使用换行符将向量的值立即写入文本文件?

Joh*_*web 45

使用std::ofstream,std::ostream_iterator并且std::copy()是通常的方法来做到这一点.下面是一个std::string使用C++ 98语法的示例(问题是在C++ 11之前提出的):

#include <fstream>
#include <iterator>
#include <string>
#include <vector>

int main()
{
    std::vector<std::string> example;
    example.push_back("this");
    example.push_back("is");
    example.push_back("a");
    example.push_back("test");

    std::ofstream output_file("./example.txt");
    std::ostream_iterator<std::string> output_iterator(output_file, "\n");
    std::copy(example.begin(), example.end(), output_iterator);
}
Run Code Online (Sandbox Code Playgroud)

  • 你写的"问题是在C++ 11之前被问到的" - C++ 11还有其他方法可以做到这一点吗? (20认同)
  • 您应该小心使用字符串作为示例.因为加载字符串向量的相反方法是不同的(它是输出/输入不同的唯一标准类型). (3认同)

Phl*_*das 14

假设你有C++ 11:

#include <fstream>
#include <vector>
#include <string>

int main()
{
    std::vector<std::string> v{ "one", "two", "three" };
    std::ofstream outFile("my_file.txt");
    // the important part
    for (const auto &e : v) outFile << e << "\n";
}
Run Code Online (Sandbox Code Playgroud)

  • 如果您想将整行浮点数据向量写入二进制文件怎么办? (4认同)

Pet*_*ter 5

也许我错过了什么,但有什么不对:

std::ofstream f("somefile.txt");
for(vector<X>::const_iterator i = v.begin(); i != v.end(); ++i) {
    f << *i << '\n';
}
Run Code Online (Sandbox Code Playgroud)

这避免了必须进行潜在的二次字符串连接,我认为这会破坏你的运行时间.