【问题标题】:Using ostream_iterator to copy a map into file使用 ostream_iterator 将地图复制到文件中
【发布时间】:2017-04-03 01:47:25
【问题描述】:

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

map<string, int> M;

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

错误信息错误:没有匹配的函数调用 'std::ostream_iterator, int>::ostream_iterator(std::ofstream&, const char [2])'|

既然 map M 是一个 type ,为什么 ostream_iterator 不取它的 type 呢?

【问题讨论】:

标签: c++ c++11 stl std


【解决方案1】:

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

std::map M 中元素的类型是std::pair。但是您不能将 std::pair 作为第一个模板参数,因为没有默认方式来打印 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;
    }
);

【讨论】:

    猜你喜欢
    • 2013-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-15
    • 2016-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多