Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
335 views
in Technique[技术] by (71.8m points)

c++ - How to write vector values to a file

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.

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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, "
");
    std::copy(example.begin(), example.end(), output_iterator);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...