Reputation: 853
what will be the fastest way to write a std::vector
(or any contiguous container for that matter) to a file that's not in binary (i.e. text mode)? In my case, speed is important and the vectors are continuously produced and written to file.
In binary mode it is fairly straight forward since std::vector
is contiguous in memory. Note i do not want to depend on Boost Serialization. (although i may be forced to if its the most elegant way...). Also I need a sequence of characters to separate elements (i.e. a space)
This is what I'm doing at the moment (is an example) but this is very generic even if I wrote an operator <<
for a vector
. Is there a more optimized version of this code or am I left with this?
std::ofstream output(...);
...
template <typename T>
write_vec_to_file (const &std::vector<T> v)
{
for (auto i: v)
output << i << " ";
output << "\n";
}
As a side question, if one keeps calling std::cout << ...
is there an overhead just to start std::cout
? My guess would obviously be yes
Upvotes: 4
Views: 1243
Reputation: 74078
You can use std::copy
for example
std::vector<int> v = { 1, 2, 3, 4, 5 };
std::copy(v.begin(), v.end(), std::ostream_iterator<int>(std::cout, " "));
Upvotes: 3