STL中unordered_map的常用方法

官方文档有比本文更加全面的API说明:

http://www.cplusplus.com/reference/unordered_map/unordered_map/

以下主要记录一些最常用的API:

#include<unordered_map>
using namespace std;

int main()
{
	unordered_map <string, int> hash;
	
	//以下是三种插入键值对的方法
	hash["Apple"] = 1;   //如果原先没有该pair,则会插入该pair。如果有,则会修改value值
	hash.insert(make_pair("Orange", 2));
	hash.insert(pair<string,int>("Banana", 3));
	
	//以下是两种查找key是否存在于unordered_map的方法
	if (hash.find("Apple") != hash.end()) //方法一:查找key是否在map中
		cout << "Apple exists"<<endl;
	if (hash.count("Banana") != 0)  //方法二:查找key是否在map中
		cout << "Banana exists" << endl;

	//以下是两种遍历key和value的方式
	for (auto iter = hash.begin(); iter != hash.end(); ++iter)
		cout << "first :" << iter->first << "second :" << iter->second << endl;
	for (auto element : hash)
		cout << "first :" << element.first << "second :" << element.second << endl;

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值