c – 使用`std :: pair`值进入`std :: unordered_map`
作者:互联网
参见英文答案 > std::map emplace without copying value 2个
我正试图将值放入std :: unordered地图,如下所示:
std::unordered_map<std::string, std::pair<std::string, std::string>> testmap;
testmap.emplace("a", "b", "c"));
这是行不通的,原因是:
error C2661: ‘std::pair::pair’ : no overloaded function takes 3 arguments
我已经看了this answer和this answer,似乎我需要将std :: piecewise_construct合并到安置中以使其工作,但我不认为我完全知道在这种情况下把它放在哪里.尝试像
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
有什么办法可以让这些价值得到安抚吗?
我正在编译msvc2013,以防万一.
解决方法:
您需要使用std :: piecewise_construct和std :: forward_as_tuple作为参数.
以下编译:
#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;
}
标签:unordered-map,std-pair,c,c11 来源: https://codeday.me/bug/20190829/1759627.html