How to write vector values to a file

Viewed 117477

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?

4 Answers

Assuming you have 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";
}
Related