Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1683315
  • 博文数量: 347
  • 博客积分: 9328
  • 博客等级: 中将
  • 技术积分: 2680
  • 用 户 组: 普通用户
  • 注册时间: 2010-07-29 23:45
文章分类

全部博文(347)

文章存档

2016年(1)

2013年(4)

2012年(207)

2011年(85)

2010年(50)

分类: C/C++

2012-12-15 10:44:28

GCC:
#include 

using namespace __gnu_cxx;

struct compare_str
{
    bool operator()(const char* p1, const char*p2) const
    {
        return strcmp(p1, p2) == 0;
    }
};

int main(int argc, char* argv[])
{
    hash_map, compare_str> StrIntMap;
    StrIntMap["a"] = 111;
    StrIntMap["b"] = 222;
    return 0;
}


VC:

  1. #include <hash_map>
  2. using namespace std;
  3. using namespace stdext; 

  4. struct CharLess : public binary_function<const char*, const char*, bool>
  5. {
  6. public:
  7.     result_type operator()(const first_argument_type& _Left, const second_argument_type& _Right) const
  8.     {
  9.         return(stricmp(_Left, _Right) < 0 ? true : false);
  10.     }
  11. }; 

  12. hash_map<const char*, int, hash_compare<const char*, CharLess> > CharHash;
  13. CharHash["a"] = 123;
  14. CharHash["b"] = 456;
  15. char szInput[64] = "";
  16. scanf("%s", szInput);
  17. int val = CharHash[szInput];
若是int类型,可以不设置比较器,但对于指针类型则不行,例如char*。例如,下面的代码就会去比较"a"和"b"这两个常量的指针大小,这个时候就需要上面的比较器了。
参考:http://blog.csdn.net/srzhz/article/details/7881946

  1. hash_map<const char*, int> CharHash;  
  2. CharHash["a"] = 123;  
  3. CharHash["b"] = 456;  
  4. char szInput[64] = "";  
  5. scanf("%s", szInput);  
  6. int val = CharHash[szInput]; 
阅读(3642) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~