如何将向量值写入文件 [英] How to write vector values to a file

查看:170
本文介绍了如何将向量值写入文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的向量很大。

我使用的方式极大地增加了程序的运行时间。首先是将所有值写入使用 stringstreams 计算的字符串,然后将字符串写入文件。另一种方法是在事实之后制作一个长字符串并将其写入文件。但是,这两者都很慢。

The ways that I use multiply the run-time of the program hugely. The first is write all values to a string as they are calculated using stringstreams and later write the string to a file. The other method is to make a long string after the fact and write that to the file. However, both of these are very slow.

有没有一种方法可以立即将换行符的矢量立即插入换行符中?

Is there a way to just write the vector's values to the text file immediately with line breaks?

推荐答案

使用 std :: ofstream std :: ostream_iterator std :: copy() 是执行此操作的常用方法。这是 std :: string 使用C ++ 98语法(此问题在C ++ 11之前问):

Using std::ofstream, std::ostream_iterator and std::copy() is the usual way to do this. Here is an example with std::strings using C++98 syntax (the question was asked pre-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);
}

这篇关于如何将向量值写入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆