sgi stl中的hash_map使用请参加http://www.stlchina.org/twiki/bin/view.pl/Main/STLDetailHashMap
在vc中(本文以vc2003为编译环境),hash_map与sgi stl中的定义是不一样的,区别如下:
vc:
template<class _Kty,
 class _Ty,
 class _Tr = hash_compare<_Kty, _STD less<_Kty> >,
 class _Alloc = _STD allocator< _STD pair<const _Kty, _Ty> > >
 class hash_map
{
}
sgi:
template <class _Key, class _Tp, class _HashFcn = hash<_Key>,
class _EqualKey = equal_to<_Key>,
class _Alloc = __STL_DEFAULT_ALLOCATOR(_Tp) >
class hash_map
{
}
可以看出,vc中把hash函数和比较函数(并且是“严格弱小于”)都整合到一起了,就是hash_compare,而在sgi中,两者是分开的,分别是两个不同的仿函数。
在这里,我们举一个在vs中用hash_map保存自定义类的例子,关键之处是定义合适的hash_compare。
详情看代码~~
//1 define the class
class ClassA{
public:
 ClassA(int a):m_a(a){}
 int getvalue()const { return m_a;}
 void setvalue(int a){m_a;}
private:
 int m_a;
};
//2 define the hash function
struct my_hash_compare : public stdext::hash_compare<ClassA>
{ 
 size_t operator()(const ClassA & A)const
 {
  return A.getvalue();
 }
 bool operator()(const ClassA & a1, const ClassA & a2)const
{
  return  a1.getvalue() < a2.getvalue();
 }
};
int _tmain(int argc, _TCHAR* argv[])
{
  hash_map<ClassA, string, my_hash_compare> hmap;
 ClassA a1(1);
 ClassA a2(2);
 hmap[a1] = "a";
 hmap[a2] = "b";
 ClassA a3(1);
 if (hmap.find(a3) != hmap.end())
 {
  cout << "find ok" << endl;
 }
return 0;
}
	posted on 2009-04-29 14:00 
水 阅读(2761) 
评论(3)  编辑 收藏 引用  所属分类: 
vc