Hash Table 哈希表 C++ 例子

本文介绍了哈希表的基本概念及其为何重要,并通过实例展示了如何使用哈希函数快速查找元素。此外,还提供了两种不同复杂度的哈希表类实现,包括简单的整数查找和更复杂的键值对存储。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

What's a Hash Table? Why we need a Hash Table?


By Using a Hash Table we can find element very quickly. For example, There are 20 random number in an array below.



It's not a sorted array, So We can not use Binary Search to finding a number, When we need to find  118, We need 12 comparisons! Finding number like 270, 198, we need even more comparison.


We change the way the 20 number store. We store them in 10 linked lists. There is a rule, If the number's last digit is 0, so we insert it in a  linked list which  index is 0. Look at  the Figure 1 for more detail. like number 118, it's last digit is 8, so we  insert it in ninth linked list.



So in this way, We find 118 only need 1 comparison in the ninth linked list! Finding number like 270 or 198, we need just 2 comparisons.


Hash Function


Note that the basic hash table which we explained above used a modulo function. There are many way to hash data, but modulo is the most common. What's more, the modulo function often use a prime number. That was because you get fewer collisions when you modulo a key  by a prime number. Having fewer collisions makes your table easier to work and more efficient. There is a completed mathmatical reasoning behind this, but it is okay for us to assume that this is true for us.


A Hash Table Class Example


You need have some STD knowledge, We will use "list" in STD instead of using customied linked list. And we also use  "find" and "erase" function.


  1. #ifndef _HASHTABLE_   
  2. #define _HASHTABLE_   
  3.   
  4. #include <list>   
  5. #include <algorithm>   
  6.   
  7. using namespace std;  
  8.   
  9. class HashTable{  
  10.   
  11. private:  
  12.     list<int> containers[10];  
  13.     int HashFunction(const int& v) const;  
  14.     int count;  
  15.   
  16. public:  
  17.     HashTable();  
  18.     ~HashTable();  
  19.     void Insert(const int& e);  
  20.     bool Find(const int& e) const;  
  21.     bool Delete(const int& e);  
  22.     int Count() const;  
  23. };  
  24.   
  25. int HashTable::HashFunction(const int& v) const{  
  26.     return v%10;  
  27. }  
  28.   
  29. HashTable::HashTable(){  
  30.     count = 0;  
  31. }  
  32.   
  33. HashTable::~HashTable(){  
  34.     count = 0;  
  35.     for(int i = 0; i< 10; ++i){  
  36.         containers[i].clear();  
  37.     }  
  38. }  
  39.   
  40. void HashTable::Insert(const int& e){  
  41.     const int hashResult = HashFunction(e);  
  42.     containers[hashResult].push_back(e);  
  43.     ++count;  
  44. }  
  45.   
  46. bool HashTable::Find(const int& e) const{  
  47.     const int hashResult = HashFunction(e);  
  48.     list<int>::const_iterator itr = find(containers[hashResult].begin(),  
  49.         containers[hashResult].end(), e);  
  50.     if(itr != containers[hashResult].end()){  
  51.         return true;  
  52.     }else{  
  53.         return  false ;  
  54.     }  
  55. }  
  56.   
  57. bool HashTable::Delete(const int& e){  
  58.     const int hashResult = HashFunction(e);  
  59.     list<int>::iterator itr = find(containers[hashResult].begin(),  
  60.         containers[hashResult].end(), e);  
  61.     if(itr != containers[hashResult].end()){  
  62.         containers[hashResult].erase(itr);  
  63.         --count;  
  64.         return true;  
  65.     }else{  
  66.         return false;  
  67.     }  
  68.   
  69. }  
  70.   
  71. int HashTable::Count()const{  
  72.     return count;  
  73. }  
  74.   
  75. #endif  
#ifndef _HASHTABLE_
#define _HASHTABLE_

#include <list>
#include <algorithm>

using namespace std;

class HashTable{

private:
	list<int> containers[10];
	int HashFunction(const int& v) const;
	int count;

public:
	HashTable();
	~HashTable();
	void Insert(const int& e);
	bool Find(const int& e) const;
	bool Delete(const int& e);
	int Count() const;
};

int HashTable::HashFunction(const int& v) const{
	return v%10;
}

HashTable::HashTable(){
	count = 0;
}

HashTable::~HashTable(){
	count = 0;
	for(int i = 0; i< 10; ++i){
		containers[i].clear();
	}
}

void HashTable::Insert(const int& e){
	const int hashResult = HashFunction(e);
	containers[hashResult].push_back(e);
	++count;
}

bool HashTable::Find(const int& e) const{
	const int hashResult = HashFunction(e);
	list<int>::const_iterator itr = find(containers[hashResult].begin(),
		containers[hashResult].end(), e);
	if(itr != containers[hashResult].end()){
		return true;
	}else{
		return  false ;
	}
}

bool HashTable::Delete(const int& e){
	const int hashResult = HashFunction(e);
	list<int>::iterator itr = find(containers[hashResult].begin(),
		containers[hashResult].end(), e);
	if(itr != containers[hashResult].end()){
		containers[hashResult].erase(itr);
		--count;
		return true;
	}else{
		return false;
	}

}

int HashTable::Count()const{
	return count;
}

#endif

Test the simple hash table class


  1. // SimpleHashTable.cpp : Defines the entry point for the console application.   
  2. //   
  3.   
  4. #include "stdafx.h"   
  5. #include "HashTable.h"   
  6. #include <iostream>   
  7.   
  8. using namespace std;  
  9.   
  10. int _tmain(int argc, _TCHAR* argv[])  
  11. {  
  12.     HashTable h;  
  13.     h.Insert(234);  
  14.     h.Insert(567);  
  15.     h.Insert(987);  
  16.     h.Insert(222);  
  17.     h.Insert(564);  
  18.     h.Insert(111);  
  19.   
  20.     h.Delete(234);  
  21.   
  22.     cout << boolalpha;  
  23.     cout << "Is 234 exist? " << h.Find(234)  << endl;  
  24.     cout << "Is 111 exist? " << h.Find(111) << endl;  
  25.     cout << "Total count:" << h.Count() << endl;  
  26.   
  27.     int i;  
  28.     cin >> i;  
  29.     return 0;  
  30. }  
// SimpleHashTable.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "HashTable.h"
#include <iostream>

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
	HashTable h;
	h.Insert(234);
	h.Insert(567);
	h.Insert(987);
	h.Insert(222);
	h.Insert(564);
	h.Insert(111);

	h.Delete(234);

	cout << boolalpha;
	cout << "Is 234 exist? " << h.Find(234)  << endl;
	cout << "Is 111 exist? " << h.Find(111) << endl;
	cout << "Total count:" << h.Count() << endl;

	int i;
	cin >> i;
	return 0;
}




A more completed Hash Table class


  1. #ifndef _HASHTABLE_   
  2. #define _HASHTABLE_   
  3.   
  4. #include <list>   
  5. #include <string>   
  6. #include <algorithm>   
  7.   
  8. using namespace std;  
  9.   
  10.   
  11. class Entry{  
  12. private:  
  13.     int m_key;  
  14.     string m_data;  
  15. public:  
  16.     friend bool operator == (const Entry& e1,const Entry& e2);  
  17.     Entry(){}  
  18.     Entry(const int& key,const string& data){  
  19.         m_key = key;  
  20.         m_data = data;  
  21.     }  
  22.     void setKey(const int& key){  
  23.         m_key = key;  
  24.     }  
  25.     void setData(const string& data){  
  26.         m_data = data;  
  27.     }  
  28.     int getKey()const{  
  29.         return m_key;  
  30.     }  
  31.     string getData()const{  
  32.         return m_data;  
  33.     }  
  34.       
  35. };  
  36.   
  37. bool operator ==(const Entry& e1,const Entry& e2){  
  38.     return (e1.m_key == e2.m_key);  
  39. }  
  40.   
  41.   
  42. class HashTable{  
  43.   
  44. private:  
  45.     list<Entry> containers[10];  
  46.     int HashFunction(const int& v) const;  
  47.     int count;  
  48.   
  49. public:  
  50.     HashTable();  
  51.     ~HashTable();  
  52.     void Insert(const Entry& entry);  
  53.     bool Find(const int& key,list<Entry>::const_iterator& itr) const;  
  54.     bool Delete(const int& key);  
  55.     int Count() const;  
  56. };  
  57.   
  58. int HashTable::HashFunction(const int& v) const{  
  59.     return v%10;  
  60. }  
  61.   
  62. HashTable::HashTable(){  
  63.     count = 0;  
  64. }  
  65.   
  66. HashTable::~HashTable(){  
  67.     count = 0;  
  68.     for(int i = 0; i< 10; ++i){  
  69.         containers[i].clear();  
  70.     }  
  71. }  
  72.   
  73. void HashTable::Insert(const Entry& entry){  
  74.     const int hashResult = HashFunction(entry.getKey());  
  75.     containers[hashResult].push_back(entry);  
  76.     ++count;  
  77. }  
  78.   
  79. bool HashTable::Find(const int& key,list<Entry>::const_iterator& out) const{  
  80.     const int hashResult = HashFunction(key);  
  81.     Entry entry;  
  82.     entry.setKey(key);  
  83.     list<Entry>::const_iterator itr = find(containers[hashResult].begin(),  
  84.         containers[hashResult].end(), entry);  
  85.     if(itr != containers[hashResult].end()){  
  86.          out = itr;  
  87.          return true;  
  88.     }else{  
  89.         return  false ;  
  90.     }  
  91. }  
  92.   
  93. bool HashTable::Delete(const int& key){  
  94.     const int hashResult = HashFunction(key);  
  95.     Entry entry;  
  96.     entry.setKey(key);  
  97.     list<Entry>::iterator itr = find(containers[hashResult].begin(),  
  98.         containers[hashResult].end(), entry);  
  99.     if(itr != containers[hashResult].end()){  
  100.         containers[hashResult].erase(itr);  
  101.         --count;  
  102.         return true;  
  103.     }else{  
  104.         return false;  
  105.     }  
  106.   
  107. }  
  108.   
  109. int HashTable::Count()const{  
  110.     return count;  
  111. }  
  112.   
  113. #endif  
#ifndef _HASHTABLE_
#define _HASHTABLE_

#include <list>
#include <string>
#include <algorithm>

using namespace std;


class Entry{
private:
	int m_key;
	string m_data;
public:
	friend bool operator == (const Entry& e1,const Entry& e2);
	Entry(){}
	Entry(const int& key,const string& data){
		m_key = key;
		m_data = data;
	}
	void setKey(const int& key){
		m_key = key;
	}
	void setData(const string& data){
		m_data = data;
	}
	int getKey()const{
		return m_key;
	}
	string getData()const{
		return m_data;
	}
	
};

bool operator ==(const Entry& e1,const Entry& e2){
	return (e1.m_key == e2.m_key);
}


class HashTable{

private:
	list<Entry> containers[10];
	int HashFunction(const int& v) const;
	int count;

public:
	HashTable();
	~HashTable();
	void Insert(const Entry& entry);
	bool Find(const int& key,list<Entry>::const_iterator& itr) const;
	bool Delete(const int& key);
	int Count() const;
};

int HashTable::HashFunction(const int& v) const{
	return v%10;
}

HashTable::HashTable(){
	count = 0;
}

HashTable::~HashTable(){
	count = 0;
	for(int i = 0; i< 10; ++i){
		containers[i].clear();
	}
}

void HashTable::Insert(const Entry& entry){
	const int hashResult = HashFunction(entry.getKey());
	containers[hashResult].push_back(entry);
	++count;
}

bool HashTable::Find(const int& key,list<Entry>::const_iterator& out) const{
	const int hashResult = HashFunction(key);
	Entry entry;
	entry.setKey(key);
	list<Entry>::const_iterator itr = find(containers[hashResult].begin(),
		containers[hashResult].end(), entry);
	if(itr != containers[hashResult].end()){
         out = itr;
		 return true;
	}else{
		return  false ;
	}
}

bool HashTable::Delete(const int& key){
	const int hashResult = HashFunction(key);
	Entry entry;
    entry.setKey(key);
	list<Entry>::iterator itr = find(containers[hashResult].begin(),
		containers[hashResult].end(), entry);
	if(itr != containers[hashResult].end()){
		containers[hashResult].erase(itr);
		--count;
		return true;
	}else{
		return false;
	}

}

int HashTable::Count()const{
	return count;
}

#endif

Test the completed hash table class


  1. // HashTableApp.cpp : Defines the entry point for the console application.   
  2. //   
  3.   
  4. #include "stdafx.h"   
  5. #include "HashTable.h"   
  6. #include <iostream>   
  7. #include <string>   
  8.   
  9. using namespace std;  
  10.   
  11. int _tmain(int argc, _TCHAR* argv[])  
  12. {  
  13.     HashTable h;  
  14.     h.Insert(Entry(234,"one"));  
  15.     h.Insert(Entry(567,"two"));  
  16.     h.Insert(Entry(987,"three"));  
  17.     h.Insert(Entry(222,"four"));  
  18.     h.Insert(Entry(564,"five"));  
  19.     h.Insert(Entry(111,"six"));  
  20.   
  21.     h.Delete(234);  
  22.   
  23.     list<Entry>::const_iterator itr;  
  24.     if(h.Find(234,itr)){  
  25.         cout <<"The data with key 234: " << itr->getData() << endl;  
  26.     }else{  
  27.         cout << "Can not find the data with key 234 " << endl;  
  28.     }  
  29.     if(h.Find(111,itr)){  
  30.         cout <<"The data with key 111: " << itr->getData() << endl;  
  31.     }else{  
  32.         cout << "Can not find the data with key 111" << endl;  
  33.     }  
  34.     cout << "Total count: " << h.Count() << endl;  
  35.   
  36.     int i;  
  37.     cin >> i;  
  38.     return 0;  
  39. }  
// HashTableApp.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "HashTable.h"
#include <iostream>
#include <string>

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
	HashTable h;
	h.Insert(Entry(234,"one"));
	h.Insert(Entry(567,"two"));
	h.Insert(Entry(987,"three"));
	h.Insert(Entry(222,"four"));
	h.Insert(Entry(564,"five"));
	h.Insert(Entry(111,"six"));

	h.Delete(234);

	list<Entry>::const_iterator itr;
	if(h.Find(234,itr)){
		cout <<"The data with key 234: " << itr->getData() << endl;
	}else{
		cout << "Can not find the data with key 234 " << endl;
	}
	if(h.Find(111,itr)){
		cout <<"The data with key 111: " << itr->getData() << endl;
	}else{
		cout << "Can not find the data with key 111" << endl;
	}
	cout << "Total count: " << h.Count() << endl;

	int i;
	cin >> i;
	return 0;
}


http://www.waitingfy.com/?p=480

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值