1

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..?

  • Braced initialization list are typeless, and cannot be perfect-forwarded to a constructor via a template, like `std::map::insert`. – Sam Varshavchik Aug 28 '22 at 15:20
  • 2
    `std::unordered_map::insert` doesn't take two parameters. Or at least, it doesn't take key and value as two separate parameters. `map.insert({1, { 2, 3.4 }});` [works](https://godbolt.org/z/z9fYa4EsY) – Igor Tandetnik Aug 28 '22 at 15:21
  • 2
    Off the top of my head, `map.emplace(1, Example{ 2, 3.4 });` – john Aug 28 '22 at 15:24
  • 2
    @SamVarshavchik I don't see how this is relevant? It doesn't work because `insert` doesn't accept parameters like these. It would work with `emplace()` call or if the pair was constructed using another pair of braces. I replaced the duplicate target for now, but maybe I'm wrong. – Yksisarvinen Aug 28 '22 at 15:25
  • I reopened the question, because of invalid close reason. See also @John's and Yksisarvinen's comment and existing answer. – Olaf Dietsche Aug 28 '22 at 15:31
  • @OlafDietsche Is [What is the preferred/idiomatic way to insert into a map?](https://stackoverflow.com/questions/4286670/what-is-the-preferred-idiomatic-way-to-insert-into-a-map) an incorrect duplicate target? It answers in greater detail how to correctly insert elements into map and mentions `emplace()` (which answer here fails to do). – Yksisarvinen Aug 28 '22 at 15:33
  • @Yksisarvinen I wouldn't consider the question, but at least one of the top answers point into the right direction. – Olaf Dietsche Aug 28 '22 at 15:36

1 Answers1

2

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

Olaf Dietsche
  • 72,253
  • 8
  • 102
  • 198
Sungwon
  • 36
  • 2