3

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.

Community
  • 1
  • 1
Nicolas Holthaus
  • 7,763
  • 4
  • 42
  • 97

1 Answers1

5

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;
}
wally
  • 10,717
  • 5
  • 39
  • 72