c++ 如何将矢量值写入文件

mzillmmw  于 2022-12-30  发布在  其他
关注(0)|答案(4)|浏览(127)

我有一个很大的向量。
我使用的方法大大增加了程序的运行时间。第一种方法是在使用stringstreams计算值时将所有值写入字符串,然后将该字符串写入文件。另一种方法是在实际操作之后创建一个长字符串并将其写入文件。然而,这两种方法都非常慢。
有没有一种方法可以将向量的值直接写入文本文件,并使用换行符?

vsnjm48y

vsnjm48y1#

使用std::ofstreamstd::ostream_iteratorstd::copy()是实现这一点的常用方法。下面是一个使用C98语法的std::string的例子(这个问题在C11之前就提出了):

#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);
}
zvokhttg

zvokhttg2#

假设您有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";
}
dojqjjoe

dojqjjoe3#

也许我错过了什么,但有什么问题:

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

这样就避免了进行二次字符串连接,我认为这是导致运行时失败的原因。

相关问题