Chinaunix首页 | 论坛 | 博客
  • 博客访问: 921125
  • 博文数量: 158
  • 博客积分: 4380
  • 博客等级: 上校
  • 技术积分: 2367
  • 用 户 组: 普通用户
  • 注册时间: 2006-09-21 10:45
文章分类

全部博文(158)

文章存档

2012年(158)

我的朋友

分类: C/C++

2012-11-23 15:07:06

#define TESTHASHMAP 1      // 为0使用map,为1使用hash_map,可以对照看看结果

#if TESTHASHMAP != 0
#include
using namespace __gnu_cxx;
#else
#include
#endif
#include
using namespace std;

struct eqstr
{
#if TESTHASHMAP != 0
    bool operator()( const int& s1, const int& s2 ) const  // 没有这个函数编译报错,有了嘛却又从来不调用
    {
        printf( "-" );
        return ((s1/10)==(s2/10));
    }
#else
    bool operator()( const int& s1, const int& s2 ) const
    {
        return ((s1/10)<(s2/10));
    }
#endif
};

int main()
{
#if TESTHASHMAP != 0
    typedef hash_map, eqstr> TYPE;
#else
    typedef map TYPE;
#endif

    TYPE test;
    test[31] = 31;
    test[32] = 32;
    test[41] = 41;
    for( TYPE::const_iterator itor=test.begin(); itor!=test.end(); ++itor )
    {
        cout << '(' << itor->first << ',' << itor->second << ')' << endl;
    }
    if( test.find(33) != test.end() )
        cout << "succeed" << endl;
    else
        cout << "fail" << endl;

    system( "pause" );
}

------------------------------------------------------------------

使用map输出:
(31,32)
(41,41)
succeed

使用hash_map输出:
(31,31)
(32,32)
(41,41)
fail

阅读(1034) | 评论(2) | 转发(0) |
给主人留下些什么吧!~~

网友评论2012-11-23 15:07:58

周星星
#include <iostream>
#include <ext/hash_map>
using namespace std;
using namespace __gnu_cxx;

struct myhash
{
    size_t operator()(int __x) const
    {
        return __x%10;
    }
};
struct myequal
{
    bool operator()( const int& s1, const int& s2 ) const
    {
  &n

网友评论2012-11-23 15:07:45

heroboy
没有错
因为31,32有不同的hash value
而eqstr是用来在对于hash value相同情况下排序的
msdn:
For any value _Key1 of type Key that precedes _Key2 in the sequence and has the same hash value (value returned by the hash function), hash_comp(_Key2, _Key1) is false.

只有hash value相同才会考虑用eqstr比较