No matching member function for call to “insert” std::unordered_map

给你一囗甜甜゛ 提交于 2019-12-08 02:34:37

问题


I am trying to hash a string to a pointer to a void function which takes in a string. I get the following error when trying to insert my key value pair into the map:

"No matching member function for call to "insert"

I am not sure how to interpret this error.

I think I'm either passing in the wrong type for insert, the function reference incorrectly, or typedef'ing a function pointer wrong.

#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); 
}   

Any advice would be appreciated.


回答1:


If you look at the overloads for std::unordered_map::insert, you'll see these:

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 );

There is no insert(key_type, mapped_type), which is what you're trying to do. What you meant was:

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



回答2:


If you want to place a new entry in the map, without actually making a new entry (aka std::pair), then use one of these two forms:

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

The method insert is only for adding PAIRS to the map.
If you need to use insert, then you must make a pair, as @Barry illustrated in his answer.




回答3:


The following code is working fine.

#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));
}  

You have to use std::make_pair to insert the value.



来源:https://stackoverflow.com/questions/33613983/no-matching-member-function-for-call-to-insert-stdunordered-map

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!