C++:在C或c++中,最快地将矢量文件以普通文本模式(非二进制)输出

时间:2022-03-21 14:03:29

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.

将std::vector(或任何相邻的容器)写入一个没有二进制文件(即文本模式)的文件,最快的方法是什么?在我的例子中,速度很重要,向量是连续生成并写入文件的。

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)

在二进制模式中,由于std::vector在内存中是连续的,所以它是相当直接的。注意,我不想依赖于Boost序列化。(虽然我可能不得不说这是最优雅的方式……)我还需要一个字符序列来分隔元素(即空格)

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

作为一个附加问题,如果有人一直调用std::cout <…是否有额外的开销来启动std::cout?我的猜测显然是肯定的

1 个解决方案

#1


3  

You can use std::copy for example

例如,您可以使用std::copy

std::vector<int> v = { 1, 2, 3, 4, 5 };
std::copy(v.begin(), v.end(), std::ostream_iterator<int>(std::cout, " "));

#1


3  

You can use std::copy for example

例如,您可以使用std::copy

std::vector<int> v = { 1, 2, 3, 4, 5 };
std::copy(v.begin(), v.end(), std::ostream_iterator<int>(std::cout, " "));