1. 程式人生 > >hash_map自定義資料型別作key

hash_map自定義資料型別作key

#include <iostream>
#include <ext/hash_map>

/*
 * 自定義資料型別作為hash_map的key值.
 * 注意底層hashtable的key值不可改變,所以這裡的 == 及 () 運算子過載均採用const修飾.
 */

using namespace std;
using __gnu_cxx::hash_map;

// 自定義資料型別
struct Node{
	Node(int k, int val) : key(k), value(val){
	}
	int key;
	int value;
	bool operator==(const Node &node) const{
		return (node.key == key && node.value == value);
	}
};

// 方法一
struct node_hash_1{
		size_t operator()(const Node &node) const{
		return size_t(node.key);
	}
};

// 方法二(特化版本)
template <class T>
struct node_hash_2{};
template <>
struct node_hash_2<Node>{
	size_t operator()(const Node &node) const{
		return size_t(node.key);
	}
};

// windows版本
//struct node_hash_3{
//	enum
//	{	// parameters for hash table
//		bucket_size = 1		// 0 < bucket_size
//	};
//	size_t operator()(const Node& _Keyval) const
//	{
//		return size_t(_Keyval.key);
//	}
//	bool operator()(const Node& _Left, const Node& _Right) const
//	{
//		return (_Left.key < _Right.key || _Left.value < _Right.value ? true : false);
//	}
//};

int main()
{
	{
		// 方法一
		typedef hash_map<Node, int, node_hash_1 > HashTest_1;
		// 方法二
		typedef hash_map<Node, int, node_hash_2<Node> > HashTest_2;
		// windows 版本
		//typedef hash_map<Node, int, node_hash_3 > HashTest_3;
		
		//HashTest_1 test;
		//HashTest_1::iterator ite;
		HashTest_2 test;
		HashTest_2::iterator ite;
		//HashTest_3 test;
		//HashTest_3::iterator ite;
		
		Node a(1, 3), b(2, 4), c(3, 8);
		test[a] = 10;
		test[b] = 20;
		test.insert(make_pair(c, 30));
		ite = test.find(c);
		if (ite != test.end()){
			cout << "c is found. [c]=" << ite->second << endl;
		}
		else{
			cout << "c is not found." << endl;
		}
	}
	
	return 0;
}