哈希在实际使用中主要是当作私有内存,对数据进行插入和查找,哈希数据元素越多,操作的时候消耗的性能就越到,最明显的是当数据元素达到哈希的容量大小时,插入数据冲突概率会变大,并慢慢的退化为数组。
本例子中将会定义一个简单的hashtable。示例如下:
#include <iostream> #include <list> #include <string> using namespace std; class CHashTable{ public: typedef list<int>::iterator ListIter; private: list<int> m_Container[3];//三个链表 int HashFunction(const int& v) const; int m_Count; public: CHashTable(); ~CHashTable(); void Insert(const int& v); bool Find(const int& v); bool Delete(const int& v); int Count() const; }; CHashTable::CHashTable(){ m_Count = 0; } CHashTable::~CHashTable(){ m_Count = 0; for(int i=0;i<3;i++){ m_Container[i].clear(); } } //哈希计算方法 int CHashTable::HashFunction(const int &v) const{ return v%3; } //插入元素 void CHashTable::Insert(const int &v){ m_Container[HashFunction(v)].push_back(v); m_Count++; } //查找元素 bool CHashTable::Find(const int &v){ int iResKey = HashFunction(v); for(ListIter it = m_Container[iResKey].begin();it != m_Container[iResKey].end();it++){ if(v == *it){ return true; } } return false; } bool CHashTable::Delete(const int& v){ int iResKey = HashFunction(v); for(ListIter it = m_Container[iResKey].begin();it != m_Container[iResKey].end();it++){ if(v == *it){ m_Container[iResKey].erase(it); m_Count --; return true; } } return false; } int CHashTable::Count() const{ return m_Count; } int main(int argc, char *argv[]) { CHashTable myhash; //initialise the hash for(int i=0;i<10;i++){A myhash.Insert(i); } //return the size of hash std::cout<<"myhash size is:"<<myhash.Count()<<endl; std::cout<<"find the element 5: "; std::string strText = myhash.Find(5)? "yeah":"oh,no"; std::cout<<strText<<std::endl; std::cout<<"del the element 5: "<<std::endl; myhash.Delete(5); std::cout<<"afther del find the element 5: "; strText = (myhash.Find(5)? "yeah":"oh,no"); std::cout<<strText<<std::endl; std::cout<<"myhash size is:"<<myhash.Count()<<endl; return 0; }