aurain
技术文摘
posts - 137,  comments - 268,  trackbacks - 0

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 阅读(2699) 评论(3)  编辑 收藏 引用 所属分类: vc

FeedBack:
# re: 在visual c++ 2003中用hash_map保存自定义类型数据
2009-04-29 20:29 | 空明流转
std::tr1::unordered_map,boost里面有的。  回复  更多评论
  
# re: 在visual c++ 2003中用hash_map保存自定义类型数据
2009-12-29 20:15 | Nova
代码根本就是错的,
bool operator()(const ClassA & a1, const ClassA & a2)const
{
return a1.getvalue() == a2.getvalue();
}
应该改为

bool operator()(const ClassA & a1, const ClassA & a2)const
{
return a1.getvalue() < a2.getvalue();
}
发表的时候自己运行一下,不然害人不浅~  回复  更多评论
  
# re: 在visual c++ 2003中用hash_map保存自定义类型数据
2009-12-31 08:51 |
@Nova
谢谢你的提醒,确实是需要这样改  回复  更多评论
  

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理



<2008年4月>
303112345
6789101112
13141516171819
20212223242526
27282930123
45678910

常用链接

留言簿(17)

随笔分类(138)

随笔档案(137)

网络开发

最新随笔

搜索

  •  

积分与排名

  • 积分 - 488858
  • 排名 - 36

最新随笔

最新评论

阅读排行榜

评论排行榜