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

Get*_*ood 2 c++ stl std c++11

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

map<string, int> M;

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

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

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

Edg*_*jān 6

如果您在声明仔细看的std :: ostream_iterator 在这里,你会发现,你的使用的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;
    }
);
Run Code Online (Sandbox Code Playgroud)