C ++: the fastest way is to write a vector file for output in normal text mode (non binary) in C or C ++

What would be the fastest way to write std::vector (or any adjacent container, for that matter), to a file that is not in binary (i.e. text mode)? In my case, speed is important, and vectors are continuously created and written to a file.

In binary mode, this is pretty straight forward, since std::vector is contiguous in memory. Note that I do not want to depend on increasing Serialization. (although I may be forced if this is the most elegant way ...). I also need a sequence of characters to separate elements (i.e. Space)

This is what I am doing at the moment (example), but it is very general even if I wrote the << 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 issue, if you call std::cout << ... , is there any overhead just to run std::cout ? I would prefer, yes.

+4
source share
1 answer

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, " ")); 
+3
source

All Articles