简体   繁体   中英

c++ struct in map as value - error “no instance of overloaded function matches the argument list”

I want to use a struct as a value in a map. Why do i have to use the value_type to insert something into the map?

#include <map>

struct myStruct {};

int main()
{
    std::map<int,myStruct> myStructMap;
    myStruct t;

    myStructMap.insert(std::map<int,myStruct>::value_type(1, t));  // OK

    myStructMap.insert(1,t);
    // Error:
    //   "no instance of overloaded function 'std::map [...]' matches
    //    the argument list"
}

Quite simply, there is no such function as std::map::insert that takes the key as one argument and the value as another.

You are expected to std::map::insert with the actual value type of the map, which is std::pair<const Key, Value> .

Sure, the C++ standard library could have provided this overload for you, but it has no reason to.

The only function that does something similar to what you're trying to do, is the C++11 emplace (and emplace_hint ):

myStructMap.emplace(1,t);

In this example, the arguments are directly forwarded to the constructor of value_type .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM