I currently write a set of doubles from a vector to a text file like this:
std::ofstream fout;
fout.open("vector.txt");
for (l = 0; l < vector.size(); l++)
fout << std::setprecision(10) << vector.at(l) << std::endl;
fout.close();
But this is taking a lot of time to finish. Is there a faster or more efficient way to do this? I would love to see and learn it.
The simplest way to write a vector to a file is to store each element of the vector on a separate line. The above code writes each string of the vector to file text. txt. We insert “endl” at the end of each string to separate the strings from one another.
A std::vector can never be faster than an array, as it has (a pointer to the first element of) an array as one of its data members. But the difference in run-time speed is slim and absent in any non-trivial program. One reason for this myth to persist, are examples that compare raw arrays with mis-used std::vectors.
std::ofstream fout("vector.txt");
fout << std::setprecision(10);
for(auto const& x : vector)
fout << x << '\n';
Everything I changed had theoretically worse performance in your version of the code, but the std::endl
was the real killer. std::vector::at
(with bounds checking, which you don't need) would be the second, then the fact that you did not use iterators.
Why default-construct a std::ofstream
and then call open
, when you can do it in one step? Why call close
when RAII (the destructor) takes care of it for you? You can also call
fout << std::setprecision(10)
just once, before the loop.
As noted in the comment below, if your vector is of elements of fundamental type, you might get a better performance with for(auto x : vector)
. Measure the running time / inspect the assembly output.
Just to point out another thing that caught my eyes, this:
for(l = 0; l < vector.size(); l++)
What is this l
? Why declare it outside the loop? It seems you don't need it in the outer scope, so don't. And also the post-increment.
The result:
for(size_t l = 0; l < vector.size(); ++l)
I'm sorry for making code review out of this post.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With