TimeCoder TimeCoder - 3 months ago 23
C++ Question

Writing Vector Values to a File

I have a large vector. Is there a simple way to write the values of the vector to a file with "\n" between every value? 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?


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;

    std::ofstream output_file("./example.txt");
    std::ostream_iterator<std::string> output_iterator(output_file, "\n");
    std::copy(example.begin(), example.end(), output_iterator);