您的位置:首页 > 其它

hash_map自定义数据类型作key

2015-12-25 13:21 423 查看
#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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: