在下面的代码中:
#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/