4

Following example code doesn't compile, I'm not able to figure out how to insert an int and tuple into the map.

#include <tuple>
#include <string>
#include <map>

int main()
{
    std::map<int, std::tuple<std::wstring, float, float>> map;
    std::wstring temp = L"sample";

    // ERROR: no instance of overloaded function matches the argument list
    map.insert(1, std::make_tuple(temp, 0.f, 0.f));

    return 0;
}

what is the correct way to insert example int, std::tuple into the map

  • you'd get the same error if your value type was eg `int`. What [overload of insert](https://en.cppreference.com/w/cpp/container/map/insert) do you think this should call ? – 463035818_is_not_an_ai Mar 28 '19 at 15:21

1 Answers1

9

Either do

map.insert(std::make_pair(1, std::make_tuple(temp, 0.f, 0.f)));

or

map.emplace(1, std::make_tuple(temp, 0.f, 0.f));

which is actually better, because it creates less temporaries.

Edit:

There is even the possibility to create no temporaries at all:

map.emplace(std::piecewise_construct, std::forward_as_tuple(1),
    std::forward_as_tuple(temp, 0.f, 0.f));
Benjamin Bihler
  • 1,612
  • 11
  • 32
  • I forgot about std::make_pair somehow and learned new stuff from your answer! –  Mar 28 '19 at 15:27
  • 1
    @zebanovich - The `std::piecewise_construct` possibility is something that also I have learned in the last couple of days. :-) – Benjamin Bihler Mar 28 '19 at 15:29