使用 ostream_iterator 将地图复制到文件中

Using ostream_iterator to copy a map into file

我有一个 STL 映射 类型 <string, int> ,我需要将该映射复制到一个文件中,但是我无法输入 [=13 类型=]

map<string, int> M;

ofstream out("file.txt");
copy( begin(M), end(M), ostream_iterator<string, int>(out , "\n") );  

Error message error: no matching function for call to 'std::ostream_iterator, int>::ostream_iterator(std::ofstream&, const char [2])'|

既然映射 M 是一个类型,为什么 ostream_iterator 不采用它的类型?

如果你仔细查看 std::ostream_iterator here 的声明,你会注意到你对 std 的使用::ostream_iterator 不正确,因为您应该将打印元素的类型指定为第一个模板参数。

std::mapM中的元素类型为std::pair.但是你不能把 std::pair< const std::string, int > 作为第一个模板参数,因为没有默认的方式来打印 std ::对.

一种可能的解决方法是使用 std::for_each 和 lambda:

std::ofstream out("file.txt");

std::for_each(std::begin(M), std::end(M),
    [&out](const std::pair<const std::string, int>& element) {
        out << element.first << " " << element.second << std::endl;
    }
);