Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting std::tuple into the std::map

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


1 Answers

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));
like image 159
Benjamin Bihler Avatar answered Oct 22 '25 18:10

Benjamin Bihler