64,654
社区成员
发帖
与我相关
我的任务
分享
//看这个吧,偶又改了下
#include <cstdlib>
#include <iostream>
#include <string>
#include <hash_map.h>
using namespace std;
struct bstr_t_hash;
struct equal_A;
class bstr_t
{
friend struct bstr_t_hash;
friend struct equal_A;
public:
bstr_t(string s):str(s){}
private:
string str;
};
struct bstr_t_hash{
size_t operator()(const bstr_t& s) const
{
unsigned long __h = 0;
for (size_t i = 0 ; i < s.str.size() ; i ++)
__h = 5*__h + s.str[i];
return size_t(__h);
}
};
struct equal_A{
bool operator()(const class bstr_t & a1, const class bstr_t & a2)const{
return a1.str == a2.str;
}
};
int main(int argc, char *argv[])
{
hash_map <bstr_t,int,bstr_t_hash,equal_A> indParams;
indParams.find(bstr_t("aaa"));
system("PAUSE");
return EXIT_SUCCESS;
}
//比如这么写:运行环境 DEV C++
#include <cstdlib>
#include <iostream>
#include <hash_map.h>
using namespace std;
struct bstr_t_hash;
class bstr_t
{
friend struct bstr_t_hash;
public:
bstr_t(string s):str(s){}
private:
string str;
};
struct bstr_t_hash{
size_t operator()(const bstr_t& s) const
{
unsigned long __h = 0;
for (size_t i = 0 ; i < s.str.size() ; i ++)
__h = 5*__h + s.str[i];
return size_t(__h);
}
};
int main(int argc, char *argv[])
{
hash_map <string,int,bstr_t_hash> indParams;
indParams.find(("aaa"));
system("PAUSE");
return EXIT_SUCCESS;
}
//int是内建类型,是内部定义好的适用类型,所以可以直接用,而自定义类型包括string,都需要自己重写哈希函数和比较函数
//怎么会不行呢,我都运行出结果了,下面的运行结果:
find sucessful!
请按任意键继续. . .
//把下面的代码粘贴到 DEV C++下的一个新工程里:
#include <cstdlib>
#include <iostream>
#include <string>
#include <hash_map.h>
using namespace std;
struct bstr_t_hash;
struct equal_A;
class bstr_t //类
{
friend struct bstr_t_hash;
friend struct equal_A;
public:
bstr_t(string s):str(s){}
private:
string str;
};
struct bstr_t_hash //哈希函数
{
size_t operator()(const bstr_t& s) const
{
unsigned long __h = 0;
for (size_t i = 0 ; i < s.str.size() ; i ++)
__h = 5*__h + s.str[i];
return size_t(__h);
}
};
struct equal_A //比较函数
{
bool operator()(const class bstr_t & a1, const class bstr_t & a2)const{
return a1.str == a2.str;
}
};
int main(int argc, char *argv[])
{
hash_map <bstr_t,int,bstr_t_hash,equal_A> indParams;
indParams.insert(hash_map <bstr_t,int,bstr_t_hash,equal_A>::value_type(bstr_t("aaa"),1));
if(indParams.find(bstr_t("aaa"))!=indParams.end())
cout<<"find sucessful!"<<endl;
system("PAUSE");
return EXIT_SUCCESS;
}