我正在向无序映射中插入记录,这会导致错误,程序如下:
#include<tr1/unordered_map>
using namespace std;
int main(int argc, char *argv[])
{
std::tr1::unordered_map<int, int> u1;
int n;
cout << "Enter the no. of times" << endl;
cin >> n;
for (int i = 0; i<n; i++)
{
int no_items;
cout << "Enter no of items" << endl;
cin >> no_items;
for (int j = 0; j<no_items; j++)
{
int key, val;
cout << "key=";
cin >> key;
cout << endl << "val=";
cin >> val;
u1.insert(std::make_pair<int, int>(key, val)); //Compiler error
//u1[key]=val; //This line is working instead of insert.
}
}
return 0;
}
u1.insert(std::make_pair<int,int>(key,val));
给出错误
- cannot convert 'key' (type 'int') to type 'int&&'
- no matching function for call to 'make_pair(int&, int&)'
想知道如何 operator []
用于将记录插入 unordered_map
正在工作并且insert()
没有功能。
最佳答案
std::make_pair
的 2 个参数是转发引用 T&&
。只需让编译器进行类型推导即可:
u1.insert(std::make_pair(key,val));
关于c++ - unordered_map::insert vs operator []= 函数给出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35439938/