[英]Move insertion with unordered_map having multiple values
我尝试了以下代码进行移动和初始化列表插入。 后者有效但不是移动插入。 有人可以帮我找到正确的解决方案吗?
#include <iostream>
#include <iostream>
#include <string>
#include <unordered_map>
using namespace std;
int main ()
{
std::unordered_map<std::string,std::pair<double, double>>
myrecipe;
myrecipe.insert (std::make_pair<std::string,std::make_pair<double,double>>("eggs",(1.0,6.0)));
myrecipe.insert ( {{"sugar",{0.8, 1.0}},{"salt",{0.1, 2.0}}} );
std::cout << "myrecipe contains:" << std::endl;
for (auto& x: myrecipe)
std::cout << x.first << ": " << x.second.first << ":" << x.second.second << std::endl;
std::cout << std::endl;
return 0;
}
这一行有几个问题:
myrecipe.insert (std::make_pair<std::string,std::make_pair<double,double>>("eggs",(1.0,6.0)));
您要插入的类型是std::pair<std::string, std::pair<double, double>>
,但这不是您在这里所做的。 这是如何使它与make_pair
工作:
myrecipe.insert(std::make_pair<std::string, std::pair<double, double>>("eggs", std::make_pair<double, double>(1.0, 6.0)));
或者以更易读的格式,依赖于模板参数类型推导:
myrecipe.insert(std::make_pair("butter", std::make_pair(2.0, 3.0)));
您需要在双打上进行配对,而不是完整的插入:
myrecipe.insert(("eggs",std::make_pair<double,double>(1.0,6.0)));
澄清:
<std::string,std::pair<double, double>>
不是std::pair
,它是一个键值对(原文如此!)。
你的std::pair<double, double>
是一个“真正的” std::pair
(或者有人可以说是一个 2 元组),它可以在 C++ 中用作std::pair
。 因此你需要std::make_pair_call
如果您将该行更改为myrecipe.insert ({"eggs",{1.0,6.0}});
它应该按预期工作
此外, std::make_pair<double,double>
不应作为模板参数出现,因为它不是类型而是返回对象的函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.