C/C++ Hash表 (五)

2014-11-24 03:28:25 · 作者: · 浏览: 1
class ClassA & a1, const class ClassA & a2)const{
return a1.getvalue() == a2.getvalue();
}
};

int main()
{
hash_map hmap;
ClassA a1(12);
hmap[a1]="I am 12";
ClassA a2(198877);
hmap[a2]="I am 198877";

cout< cout< return 0;
}

-bash-2.05b$ make my
c++ -O -pipe -march=pentiumpro my.cpp -o my
-bash-2.05b$ ./my
I am 12
I am 198877

在Visual Studio下,hash function 和 equal function 在一个结构中,不想SGI的是分开的。
class MyClass
[cpp]
{
....
};

struct my_hash
{
static const size_t bucket_size = 4;
static const size_t min_buckets = 8;
size_t operator()(const MyClass& Key) const
{
size_t hash = 999;
for (size_t i = 0; i < 100000; i++)
hash = "hash function";
return hash;
}

bool operator()(const MyClass& c1, const MyClass& c2) const
{
return "equal function";
}
};

int main()
{
hash_map my;
......
}

{
....
};

struct my_hash
{
static const size_t bucket_size = 4;
static const size_t min_buckets = 8;
size_t operator()(const MyClass& Key) const
{
size_t hash = 999;
for (size_t i = 0; i < 100000; i++)
hash = "hash function";
return hash;
}

bool operator()(const MyClass& c1, const MyClass& c2) const
{
return "equal function";
}
};

int main()
{
hash_map my;
......
}4.4如何用hash_map替换程序中已有的map容器?
这个很容易,但需要你有良好的编程风格。建议你尽量使用typedef来定义你的类型:

typedef map KeyMap;
当你希望使用hash_map来替换的时候,只需要修改:
typedef hash_map KeyMap;
其他的基本不变。当然,你需要注意是否有Key类型的hash函数和比较函数。
4.5为什么hash_map不是标准的?
具体为什么不是标准的,我也不清楚,有个解释说在STL加入标准C++之时,hash_map系列当时还没有完全实现,以后应该会成为标准。如果谁知道更合理的解释,也希望告诉我。但我想表达的是,正是因为hash_map不是标准的,所以许多平台上安装了g++编译器,不一定有hash_map的实现。我就遇到了这样的例子。因此在使用这些非标准库的时候,一定要事先测试。另外,如果考虑到平台移植,还是少用为佳。