在下面的代码中:
#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);
}
Run Code Online (Sandbox Code Playgroud)
如果我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);
^
Run Code Online (Sandbox Code Playgroud)
是否有"哈希函数无法为一对定义但仅限于基本数据类型"的行为?如果我错了,请纠正我,否则请详细说明.谢谢!
没有标准方法来计算对上的散列.你应该为你的对提供哈希函数.例如: -
struct hash_pair {
inline std::size_t operator()(const std::pair<std::string,std::string> & p) const {
return // howsoever you want to implement.
}
};
Run Code Online (Sandbox Code Playgroud)
然后将你的std :: unordered_set声明为: -
std::unordered_set< std::pair<std::string, std::string>, hash_pair> mySet;
Run Code Online (Sandbox Code Playgroud)