将成对的 C++ 向量写入文本文件

Writing C++ vector of pairs to a textfile

我有一个 vectorpair 个名为 vec1。将其写入文本文件(在 Linux 中)的(最快)方法是什么?

#include <iostream>
#include <utility>   
#include <vector>
#include <fstream>
#include <iomanip> 

int main() {
    std::vector<std::pair<int, std::vector<float>>> vec1 { {1,{0.11,0.12,0.13}},
        {2,{0.14,0.15,0.16}}, {3,{0.17,0.18,0.19}} };    
} 

我正在尝试这样的事情:

std::ofstream fout("file.txt");
fout << std::setprecision(4);

for(auto const& x : vec1)
    fout << x << '\n';

但我得到一个错误:

error: cannot bind ‘std::basic_ostream<char>’ lvalue to ‘std::basic_ostream<char>&&’

std::pair<T, U> 没有 built-in 插入运算符。您可以自己制作一个或手动打印字段:

for (auto const& x : vec1) {
    fout << x.first << ": "; 
    for (float f : x.second) fout << f << " ";
    fout << '\n';
}