Hash算法
hash算法的意义在于提供了一种快速存取数据的方法,它用一种算法建立键值与真实值之间的对应关系,(每一个真实值只能有一个键值,但是一个键值可以对应多个真实值),这样可以快速在数组等条件中里面存取数据.
例如:
//HashTable.h
template <class T>
class HashTable
{
public :
HashTable( int count ) ;
void put( T* t ,int key ) ;
T* get( int key ) ;
private :
T** tArray ;
}
//HashTable.cpp
template <Class T>
HashTable::HashTable( int count )
{
tArray = new T*[count] ;
}
template <Class T>
void HashTable::put( T* t , int key )
{
this->tArray[ key ] = t ;
}
template <Class T>
T* HashTable::get( int key )
{
return this->tArray[ key ] ;
}
这样,我们只要知道key值,就可以快速存取T类型的数据,而不用像在链表等数据结构中查找一样, 要找来找去的.
至于key值,一般都是用某种算法(所谓的Hash算法)算出来的.例如:字符串的Hash算法, char* value = "hello"; int key = (((((((27* (int)'h'+27)* (int)'e') + 27)
* (int)'l') + 27) * (int)'l' +27) * 27 ) + (int)'o' ;