简体   繁体   中英

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

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));

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