Home > Mobile >  Why cant I insert a struct value in an unordered_map C
Why cant I insert a struct value in an unordered_map C

Time:08-29

I have created a very simple example to show the problem:

#include <unordered_map>

int main() {
    struct Example {
        int num;
        float decimal;
    };

    std::unordered_map<int, Example> map;
    map.insert(1, { 2, 3.4 }); // Error none of the overloads match!
}

I should be able to insert into the map of int and struct Example but the compiler says none of the overloads match..?

CodePudding user response:

The reason for the error message is, that none of the overloads of std::unordered_map::insert takes a key and a value parameter.

You should do

map.insert({1, { 2, 3.4 }});

instead of

map.insert(1, { 2, 3.4 });

You may refer to the 6th overload of std::unordered_map::insert at https://en.cppreference.com/w/cpp/container/unordered_map/insert

  • Related