C++ 如何将向量值写入文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6406356/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to write vector values to a file
提问by TimeCoder
I have a large vector.
我有一个很大的向量。
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.
我使用的方式极大地增加了程序的运行时间。第一个是将所有值写入一个字符串,因为它们是使用计算的stringstreams
,然后将字符串写入文件。另一种方法是在事后制作一个长字符串并将其写入文件。但是,这两种方法都非常慢。
Is there a way to just write the vector's values to the text file immediately with line breaks?
有没有办法用换行符立即将向量的值写入文本文件?
回答by Johnsyweb
Using std::ofstream
, std::ostream_iterator
and std::copy()
is the usual way to do this. Here is an example with std::string
s using C++98 syntax (the question was asked pre-C++11):
使用std::ofstream
,std::ostream_iterator
和std::copy()
是执行此操作的常用方法。这是一个std::string
使用 C++98 语法的 s示例(这个问题在 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);
}
回答by Phlox Midas
Assuming you have C++11:
假设你有 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";
}
回答by Peter
Maybe I have missed something, but what is wrong with:
也许我错过了一些东西,但有什么问题:
std::ofstream f("somefile.txt");
for(vector<X>::const_iterator i = v.begin(); i != v.end(); ++i) {
f << *i << '\n';
}
That avoids having to do potentially quadratic string concatenation, which I assume is what's killing your run-time.
这避免了必须进行潜在的二次字符串连接,我认为这是杀死您的运行时间的原因。
回答by Eugen Constantin Dinca
You can use std::copyand std::ostream_iterator.