我有一个很大的向量。我使用的方法大大增加了程序的运行时间。第一种方法是在使用stringstreams计算值时将所有值写入字符串,然后将该字符串写入文件。另一种方法是在实际操作之后创建一个长字符串并将其写入文件。然而,这两种方法都非常慢。有没有一种方法可以将向量的值直接写入文本文件,并使用换行符?
stringstreams
vsnjm48y1#
使用std::ofstream,std::ostream_iterator和std::copy()是实现这一点的常用方法。下面是一个使用C98语法的std::string的例子(这个问题在C11之前就提出了):
std::ofstream
std::ostream_iterator
std::copy()
std::string
#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); }
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"; }
dojqjjoe3#
也许我错过了什么,但有什么问题:
std::ofstream f("somefile.txt"); for(vector<X>::const_iterator i = v.begin(); i != v.end(); ++i) { f << *i << '\n'; }
这样就避免了进行二次字符串连接,我认为这是导致运行时失败的原因。
6yt4nkrj4#
您可以使用std::copy和std::ostream_iterator。
4条答案
按热度按时间vsnjm48y1#
使用
std::ofstream
,std::ostream_iterator
和std::copy()
是实现这一点的常用方法。下面是一个使用C98语法的std::string
的例子(这个问题在C11之前就提出了):zvokhttg2#
假设您有C++11:
dojqjjoe3#
也许我错过了什么,但有什么问题:
这样就避免了进行二次字符串连接,我认为这是导致运行时失败的原因。
6yt4nkrj4#
您可以使用std::copy和std::ostream_iterator。