优缺点以及适用处
- 优点:
- 因为内部实现了哈希表,因此其查找速度非常的快
- 缺点:
- 哈希表的建立比较耗费时间
- 适用处,对于查找问题,unordered_map会更加高效一些,因此遇到查找问题,常会考虑一下用unordered_map
建议:大量数据的时候能达到O(1)的插入速度,比map高效,适用于大量数据查询。
头文件
c++11前面的用法:
#include<tr1/unordered_map>
using namespace std::tr1;
c++11后面的用法:
#include<unordered_map>
建立一个unordered_map
unordered_map<T,T> ma;
手动分配相对应空间
const int len=1e5;
ma.rehash(len);
数据插入
ma.insert(make_pair(value,value));
迭代器&遍历
//常规
unordered_map<int ,int>::iterator it;
//另一种
typedef unordered_map<int ,int> ump;
ump ma;
ump::iterator it;
//另另一种
for(auto&v :ma) //遍历全部
查询
//(存在的情况下)
mp.find(x)!=mp.end();
//或者
mp.count(x)!=0;
清空
mp.clear();
重点!!
自定义类
看例子
#include<bits/stdc++.h>
#include<unordered_map>
typedef long long ll;
using namespace std;
struct node{
string name;
int age;
node(string n, int a){
name = n;
age = a;
}
bool operator==(const node & p) const
{
return name == p.name && age == p.age;
}
};
struct hash_name{
size_t operator()(const node & p) const{
return hash<string>()(p.name) ^ hash<int>()(p.age);
}
};
int main(int argc, char* argv[]){
unordered_map<node, int, hash_name> ump;
ump[node("Mark", 17)] = 40561;
ump[node("Andrew",16)] = 40562;
for ( auto it = ump.begin() ; it != ump.end() ; it++ )
cout << it->first.name<< " " << it->first.age<< " : " << it->second<< endl;
return 0;
}