stl中hash_map的使用,该如何解决
stl中hash_map的使用
我采用如下方式定义一个结构体
struct POINT{
double x;
double y;
};
#include<hash_map>
using namespace stdext;
hash_map<int ,POINT> PtHash;
然后想通过hash_map的find函数查找当前点POINT是否与hashmap中的相等,该如何做呢?求指点,谢谢!
------解决方案--------------------
我采用如下方式定义一个结构体
struct POINT{
double x;
double y;
};
#include<hash_map>
using namespace stdext;
hash_map<int ,POINT> PtHash;
然后想通过hash_map的find函数查找当前点POINT是否与hashmap中的相等,该如何做呢?求指点,谢谢!
------解决方案--------------------
- C/C++ code
// hash_map_find.cpp // compile with: /EHsc #define _DEFINE_DEPRECATED_HASH_CLASSES 0 #include <hash_map> #include <iostream> int main( ) { using namespace std; using namespace stdext; hash_map <int, int> hm1; hash_map <int, int> :: const_iterator hm1_AcIter, hm1_RcIter; typedef pair <int, int> Int_Pair; hm1.insert ( Int_Pair ( 1, 10 ) ); hm1.insert ( Int_Pair ( 2, 20 ) ); hm1.insert ( Int_Pair ( 3, 30 ) ); hm1_RcIter = hm1.find( 2 ); cout << "The element of hash_map hm1 with a key of 2 is: " << hm1_RcIter -> second << "." << endl; // If no match is found for the key, end( ) is returned hm1_RcIter = hm1.find( 4 ); if ( hm1_RcIter == hm1.end( ) ) cout << "The hash_map hm1 doesn't have an element " << "with a key of 4." << endl; else cout << "The element of hash_map hm1 with a key of 4 is: " << hm1_RcIter -> second << "." << endl; // The element at a specific location in the hash_map can be found // using a dereferenced iterator addressing the location hm1_AcIter = hm1.end( ); hm1_AcIter--; hm1_RcIter = hm1.find( hm1_AcIter -> first ); cout << "The element of hm1 with a key matching " << "that of the last element is: " << hm1_RcIter -> second << "." << endl; } Copy Code The element of hash_map hm1 with a key of 2 is: 20. The hash_map hm1 doesn't have an element with a key of 4. The element of hm1 with a key matching that of the last element is: 30.
------解决方案--------------------
你的key是int,却要找一个POINT,设计有问题,非要找的话,只能自己遍历来找。
map的key才是用来查找的。
------解决方案--------------------
既然是map,当然要使用其高速查找的特性,如果你通过遍历去查找,当然也是能查找的,此时map容器就退化为vector了,甚至比vector效率还差。
每个容器都有自己的优点缺点,如果你非要用其弱点,那就本末倒置了。