c++ hash_map等用法的小tips

c++的hash_map

stl没有hash_map,但有个<ext/hash_map>,位于namespace __gnu_cxx下,试一下如下code,可以验证一下系统是否已经安装ext

#include <ext/hash_map>
#include <iostream>

using namespace std;
using __gnu_cxx::hash_map;

void Print(const hash_map<int, int>& hm) {
  for (hash_map<int, int>::const_iterator it = hm.begin();
       it != hm.end(); ++it) {
    cout << it->first << ", " << it->second << endl;
  }
}

int main() {
  hash_map<int, int> hm;
  hm[1] = 3;
  hm[2] = 4;
  Print(hm);
}


一些小tips

其实map,set等也类似,姑且以更fancy的hash_map来说明,呵呵

1. 不用在等号右侧用[],比如:

hm_a[i] = hm_b[i];  // wrong

因为hm_b[i]如果不存在的话,将会被创建

需要用替换:

hm_a[i] = hm_b->find(i)->second;  // correct

2. 想更新hash_map的时候
hm_a[key1] = sth;
...
hm_a.erase(key2);
这样的code,需要当心key1和key2不相等,否则就都被删掉,白搞 


3. 用iterator删东西,不小心会出错,比如iterator失效等,举一例普通正常用法如下:

void Filter(const int key, hash_map<int, int>* hm) {
  for (hash_map<int, int>::iterator it = hm->begin(); it != hm->end();) {
    if (it->first == key) {
      hm->erase(it++);
    } else {
      ++it;
    }
  }
}



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值