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;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值