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; }
相关文章推荐
- c#界面开发自定义快捷键
- 《开源安全运维平台:OSSIM最佳实践》内容简介
- mysql,left join on
- 状态机设定与编码选择
- Linux软件的卸载
- 转:老板,别和我谈未来
- 修改Eclipse 45秒超时
- 一、git基本常用操作
- android 界面中的各种布局
- 新打开acitivyt时,EditText焦点自动带出软键盘问题解决方法总结 ... ...
- another app is currently holding the yum lock;waiting for it to exit解决
- IOS UITextField常用的代理方法总结
- FLV科普7 FLV时间戳计算
- 用ImDisk在Windows 10中创建内存虚拟盘
- 文章标题
- 时间与果实
- JAVA-中介者设计模式
- C库函数 - fseek()
- Linux管线命令
- Monkey源代码分析之执行流程