c++ 工程基础之STL系列 (四) map

map在实际工程中应用非常广泛,基本上都会使用到,起内部实现是红黑树,查询和插入,删除复杂度都是log2(n),尤其在查询操作中非常方便,性能也很高


#include<iostream>
#include<string>
#include<map>
using namespace std;
int main()
{
	map<int, int> a;
	map<string, string> b;
	//插入有两种方式
	a[0] = 0;a[0] = 0;
	a.insert(pair<int, int>(1,1));
	cout<<"a[0]="<<a[0]<<' '<<"a[1]="<<a[1]<<endl;
	b["0"] = "123";
	b.insert(pair<string, string>("1","liuyi"));
	cout<<"b[0]="<<b["0"]<<' '<<"b[1]="<<b["1"]<<endl;

	//查找
	map<int, int>::iterator it = a.find(0);
	if(it != a.end()) 
	{
		cout<<it->first<<' '<<it->second<<endl;
	}
	//删除
	a.erase(0);
	it = a.find(0);
	if(it == a.end())
	{
		cout<<"delete a[0]"<<endl;
	}
	//清空元素
	a.clear();
	cout<<a.size()<<' '<<a.empty()<<endl;
	//切记不要用count() == 0 判断是否非空,用empty() (时间复杂度是O(1)
	cout<<a.count(0)<<endl;
	//清空内存
	a.clear();
	map<int,int>(a).swap(a);
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值