c++ - 使用 ostream_iterator 将映射复制到文件中

标签 c++ c++11 stl std

我有一个类型为 <string, int>STL 映射 ,我需要将该 map 复制到文件中,但我无法输入 ostream_iterator 的类型

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])'|

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

最佳答案

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

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

一种可能的解决方法是使用 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;
    }
);

关于c++ - 使用 ostream_iterator 将映射复制到文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40690125/

相关文章:

c++ - Makefile:没有规则来制作目标。停止

c++ - 数组分区函数

c++ - 使用 `Node*` 作为列表的迭代器

c++ - 作为对象字段的右值引用

c++ - 如何销毁通过 'Placement New' 构造的无析构函数类型

带有附加顺序的 C++ 字典/ map

c++ - CDialogEx构造函数和继承的Create()方法

异步回调中的 C++ boost-asio-network ,哪一个更好?使用 lambda 或 boost::bind()

C++ 函数模板导致输入参数出错

c++ - 仿函数和对象继承