没有匹配的成员函数来调用 "insert" std::unordered_map

No matching member function for call to "insert" std::unordered_map

本文关键字:std insert unordered map 调用 函数 成员      更新时间:2023-10-16

我正在尝试将string散列为pointer to a void function which takes in a string。当我试图将我的键值对插入到地图中时,我得到了以下错误:

"调用"insert"没有匹配的成员函数

我不知道如何解释这个错误。

我想我要么是为insert传递了错误的类型,要么是函数引用错误,要么是对函数指针进行了类型定义错误。

#include <string>
#include <unordered_map>
using namespace std;
void some_function(string arg)
{
  //some code
}
int main(int argc, const char * argv[]) {

    typedef void (*SwitchFunction)(string);
    unordered_map<string, SwitchFunction> switch_map;
    //trouble with this line
    switch_map.insert("example arg", &some_function); 
}   

如有任何建议,我们将不胜感激。

如果您查看std::unordered_map::insert的重载,您将看到以下内容:

std::pair<iterator,bool> insert( const value_type& value );
template< class P >
std::pair<iterator,bool> insert( P&& value );
std::pair<iterator,bool> insert( value_type&& value );
iterator insert( const_iterator hint, const value_type& value );
template< class P >
iterator insert( const_iterator hint, P&& value );
iterator insert( const_iterator hint, value_type&& value );
template< class InputIt >
void insert( InputIt first, InputIt last );
void insert( std::initializer_list<value_type> ilist );

没有insert(key_type, mapped_type),这就是你想要做的。你的意思是:

switch_map.insert(std::make_pair("example arg", &some_function)); 

如果您想在地图中放置一个新条目,而不需要自己实际创建新条目(也称为std::pair),则使用以下两种形式之一:

switch_map.emplace("example.org", &some_function);
// OR:
switch_map["example.org"] = &some_function;

方法insert仅用于将PAIRS添加到映射中
如果你需要使用插入,那么你必须制作一对,正如@Barry在他的回答中所示。

以下代码运行良好。

#include<iostream>
#include <string>
#include <unordered_map>
using namespace std;
void some_function(string arg)
{
    return;
  //some code
}
int main(int argc, const char * argv[]) {
typedef void (*SwitchFunction)(string);

    unordered_map<string, SwitchFunction> switch_map;
    //trouble with this line
    switch_map.insert(std::make_pair("example arg", &some_function));
}  

您必须使用std::make_pair来插入值。