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的时候
这样的code,需要当心key1和key2不相等,否则就都被删掉,白搞hm_a[key1] = sth; ... hm_a.erase(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; } } }