c++ - map 的 std::for_each() 给出无效的初始化错误

标签 c++ c++11 stl

我是 STL 的新手,尤其是算法库。 我正在尝试迭代 std::multimap,其中键和值都是 std::string 类型,使用 std::for_each() 函数并执行一些任务。

这是我的std::multimap:

std::multimap<std::string, std::string> myMap;
for (int i = 0; i < 5; i++) {
    myMap.insert(std::make_pair("key", "value"));
}

这是带有 for_each() 函数的行:

std::for_each(myMap.begin(), myMap.end(), ask);

ask()函数定义如下:

void ask(std::pair<std::string, std::string>& entry) {
    // do something...
}

程序给我以下错误:

error: invalid initialization of reference of type 'std::__cxx11::basic_string&' from expression of type 'std::pair, std::__cxx11::basic_string >'

我知道,问题出在 for_each() 函数上,我认为这是因为 ask() 函数的参数不正确。 但据我所知,std::multimap 的每个条目都表示为一个 std::pair,所以 ask() 不应该> 函数以 std::pair 对象作为参数?

最佳答案

std::multimap<std::string, std::string>的元素类型是std::pair<const std::string, std::string> .注意 const

关于c++ - map 的 std::for_each() 给出无效的初始化错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54210712/

相关文章:

c++ - -Wunused-but-set-variable 当我使用 'auto' 而不是当我使用相应的类型而不是 'auto' 时发出

c++ - 通过引用返回 std::vector 导致段错误

c++ - 完美转发和临时对象的范围

c++ - 成员变量不同 "kinds"的区别

c++ - 在 C++ 程序上没有可行的重载 '='

c++ - 这个 C++ 列表有什么问题?

c++ - 右值引用的错误转发

c++ - QT 运行但 QImages 不显示在发布版本中

c++ - 映射/设置迭代器不可解除(C++)-调试声明失败?

c++ - boost::iterator_facade 和 std::find(...)