c++ - 插入适用于 set 但不适用于 unordered_set

标签 c++ c++11 set

在下面的代码中:

#include<unordered_set>
#include<iostream>
#include<utility>
#include<string>
#include<set>

using namespace std;

int main()
{
    set<pair<string, string> > g;
    pair<string, string> tmp;
    tmp.first="hello";
    tmp.second="world";
    g.insert(tmp);
}

如果我改变 set<pair<string, string> > g;unordered_set<pair<string, string> > g;插入对时出现错误,例如:

test1.cpp:15:14: note:   candidate expects 2 arguments, 1 provided
  g.insert(tmp);
              ^

是不是类似于“不能为一对定义哈希函数,而只能为基本数据类型定义哈希函数”?如果我错了请纠正我,否则请详细说明。谢谢!

最佳答案

没有计算一对散列的标准方法。您应该为您的对提供哈希函数。例如:-

struct hash_pair {
    inline std::size_t operator()(const std::pair<std::string,std::string> & p) const {
        return // howsoever you want to implement.
    }
};

然后将您的 std::unordered_set 声明为:-

std::unordered_set< std::pair<std::string, std::string>,  hash_pair> mySet;

关于c++ - 插入适用于 set 但不适用于 unordered_set,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27765133/

相关文章:

c++ - 为什么所有迭代器/迭代器适配器在 C++11 中都不可 move ?

extjs - 如何以编程方式设置选项卡(按钮)的隐藏属性

python - 在保留字典的同时将字典值转换为集合

c++ - 在 A* 遍历后从 map 中移除产生最佳路径的障碍

c++ - 关于这个抽象类的实现,我有什么不明白的?

c++ - 是什么导致 priority_queue 和 sort() 函数中的排序方式不同?

c++ - 查找范围 [a, b] 中不在给定 std::set S 中的所有数字

c++ - 关于 std::stack push 段错误的问题

c++ - 指向非指针编译错误的唯一指针

c++ - C++ 中的 char() 类型是什么?