c++ - unordered_map::insert vs operator []= 函数给出错误

标签 c++ unordered-map

我正在向无序映射中插入记录,这会导致错误,程序如下:

#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/

相关文章:

c++ - 访问 avl_set 中节点的左子节点或右子节点

C++ unordered_map 字符串与 int 键性能

c++ - unordered_map find() 和 operator []

c++ - 如何更改 Visual Studio 2017 中的命令行宏

c++ - 组合字符串 vector

C++ unordered_map 与 uint8_t

c++ - 如何在 std::tuple 中合并 std::unordered_map?

c++ - C++ STL unordered_map 如何解决冲突?

c++ - C++17中类模板的模板参数推导 : am I doing it wrong?

c++ - 作为模板参数,是否对返回类型施加约束?