为了避免额外的依赖,您可以使用std::hash http://en.cppreference.com/w/cpp/utility/hash。这是一个使用您发布的链接中的代码的示例,并更新为使用std::pair<double,double>
:
#include <unordered_map>
#include <cassert>
using namespace std;
class TPoint3D{
public:
TPoint3D(double x, double y, double z) : x(x), y(y), z(z){};
double x, y, z;
};
struct hashFunc{
size_t operator()(const TPoint3D &k) const{
size_t h1 = std::hash<double>()(k.x);
size_t h2 = std::hash<double>()(k.y);
size_t h3 = std::hash<double>()(k.z);
return (h1 ^ (h2 << 1)) ^ h3;
}
};
struct equalsFunc{
bool operator()( const TPoint3D& lhs, const TPoint3D& rhs ) const{
return (lhs.x == rhs.x) && (lhs.y == rhs.y) && (lhs.z == rhs.z);
}
};
typedef unordered_map<TPoint3D, int, hashFunc, equalsFunc> TPoint3DMap;
int main(){
TPoint3DMap myMap;
// test equalsFunc
myMap[TPoint3D(10.0, 20.0, 30.0)] = 100;
myMap[TPoint3D(10.0, 20.0, 30.0)] = 200;
assert(myMap[TPoint3D(10.0, 20.0, 30.0)] == 200);
// test if hashFunc handles well repeated values inside TPoint3D
myMap[TPoint3D(10.0, 10.0, 10.0)] = 1;
myMap[TPoint3D(10.0, 20.0, 10.0)] = 2;
myMap[TPoint3D(10.0, 10.0, 20.0)] = 3;
myMap[TPoint3D(20.0, 10.0, 10.0)] = 4;
assert(myMap[TPoint3D(10.0, 10.0, 10.0)] == 1);
assert(myMap[TPoint3D(10.0, 20.0, 10.0)] == 2);
assert(myMap[TPoint3D(10.0, 10.0, 20.0)] == 3);
assert(myMap[TPoint3D(20.0, 10.0, 10.0)] == 4);
return 0;
}
正如我之前所说,如果你想使用另一种结构,你必须适应pairHash
类和pairEquals
结构体operator()
分别适当地散列和比较新密钥。
Cheers
EDIT :
- 修改代码以使用自定义 TPPoint3D 类和统一函子类定义(均使用结构)。
- 添加了简单的测试来验证哈希和等于函子。