Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

emplace into `std::unordered_map` with `std::pair` value [duplicate]

I'm trying to emplace values into a std::unordered map like so:

std::unordered_map<std::string, std::pair<std::string, std::string>> testmap;
testmap.emplace("a", "b", "c"));

which doesn't work, due to:

error C2661: 'std::pair::pair' : no overloaded function takes 3 arguments

I've looked at this answer and this answer, and it seems like I need to incorporate std::piecewise_construct into the emplacement to get it to work, but I don't think I quite know where to put it in this case. Trying things like

testmap.emplace(std::piecewise_construct, "a", std::piecewise_construct, "b", "c"); // fails
testmap.emplace(std::piecewise_construct, "a", "b", "c"); // fails
testmap.emplace(std::piecewise_construct, "a", std::pair<std::string, std::string>( std::piecewise_construct, "b", "c")); // fails

Is there some way I can get these values to emplace?

I'm compiling with msvc2013 in case that matters.

like image 830
Nicolas Holthaus Avatar asked Sep 20 '25 14:09

Nicolas Holthaus


1 Answers

You need to use std::piecewise_construct and std::forward_as_tuple for the arguments.

The following does compile:

#include <unordered_map>

int main()
{
    std::unordered_map<std::string,std::pair<std::string,std::string>> testmap;
    testmap.emplace(std::piecewise_construct,std::forward_as_tuple("a"),std::forward_as_tuple("b","c"));
    return 0;
}
like image 79
wally Avatar answered Sep 22 '25 03:09

wally