sgi stl中的hash_map使用請(qǐng)參加http://www.stlchina.org/twiki/bin/view.pl/Main/STLDetailHashMap
在vc中(本文以vc2003為編譯環(huán)境),hash_map與sgi stl中的定義是不一樣的,區(qū)別如下:
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函數(shù)和比較函數(shù)(并且是“嚴(yán)格弱小于”)都整合到一起了,就是hash_compare,而在sgi中,兩者是分開的,分別是兩個(gè)不同的仿函數(shù)。
在這里,我們舉一個(gè)在vs中用hash_map保存自定義類的例子,關(guān)鍵之處是定義合適的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
水 閱讀(2742)
評(píng)論(3) 編輯 收藏 引用 所屬分類:
vc