c++ unordered_map

优缺点以及适用处

  • 优点: 
    • 因为内部实现了哈希表,因此其查找速度非常的快
  • 缺点: 
    • 哈希表的建立比较耗费时间
  • 适用处,对于查找问题,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;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值