求教用C++写一个结构体的hash函数
想用hash_map,求教以下结构体的一个hash函数代码structspoint{public:inta;intb;};...
想用hash_map,求教以下结构体的一个hash函数代码
struct spoint
{
public:
int a;
int b;
}; 展开
struct spoint
{
public:
int a;
int b;
}; 展开
1个回答
展开全部
#include <hash_map>
#include <string>
#include <iostream>
using namespace std;
class Spoint
{
public :
Spoint(int a=0,int b=0){this->a = a; this->b = b;}
int getA(){ return this->a ;}
int getB(){ return this->b ;}
private :
int a;
int b;
};
//1 define the hash function
struct hash_Spoint{
size_t operator()(const class Spoint & s)const{
return s.getA() + s.getB();
}
};
//2 define the equal function
struct equal_Spoint{
bool operator()(const class Spoint & s1, const class Spoint & s2)const{
return s1.getA() == s2.getA() && s1.getB() == s2.getB();
}
};
int main(int argc, char *argv[])
{
hash_map<Spoint, string, hash_Spoint, equal_Spoint> hmap;
Spoint s1(1,2);
hmap[s1]="Spoint 1";
Spoint s2(2,3);
hmap[s2]="Spoint 2";
Spoint s3(2,3);
hmap[s3]="Spoint 3";
cout<<hmap[s1]<<endl;
cout<<hmap[s2]<<endl;
cout<<hmap[s3]<<endl;
return 0;
}
#include <string>
#include <iostream>
using namespace std;
class Spoint
{
public :
Spoint(int a=0,int b=0){this->a = a; this->b = b;}
int getA(){ return this->a ;}
int getB(){ return this->b ;}
private :
int a;
int b;
};
//1 define the hash function
struct hash_Spoint{
size_t operator()(const class Spoint & s)const{
return s.getA() + s.getB();
}
};
//2 define the equal function
struct equal_Spoint{
bool operator()(const class Spoint & s1, const class Spoint & s2)const{
return s1.getA() == s2.getA() && s1.getB() == s2.getB();
}
};
int main(int argc, char *argv[])
{
hash_map<Spoint, string, hash_Spoint, equal_Spoint> hmap;
Spoint s1(1,2);
hmap[s1]="Spoint 1";
Spoint s2(2,3);
hmap[s2]="Spoint 2";
Spoint s3(2,3);
hmap[s3]="Spoint 3";
cout<<hmap[s1]<<endl;
cout<<hmap[s2]<<endl;
cout<<hmap[s3]<<endl;
return 0;
}
追问
写的太详细了,谢谢您。我的spoint代表的是一个立方体区域的网格点,hash函数返回a+b合适吗,有没有优化点儿的函数?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询