STL map的使用

14 篇文章 1 订阅
2 篇文章 0 订阅

STL map:

内部数据结构:运用红黑树,删除增加节点对其它节点没有影响,迭代器可以修改实值,不可修改key,搜索的时间复杂度未log2(n)

map的功能:
快速插入key-value记录
快速删除记录
根据key修改value
遍历所有记录

使用举例:
//noting : the key of map should define “<”
//注意:map用到的结构体需要重定义"<"运算符

#include<map>
struct axis
{
    int x;
    int y;
//noting : the key of map should define "<"
    bool operator < (const struct axis o) const
	{
		if( x != o.x)
            return x>o.x;
        else
            return y>o.y;
	}
};
map<int, string> mapStudent;
mapStudent[3] = “student_three”;//有key键可覆盖
mapStudent.insert(pair<int, string>(3, “student_three”));//有key键不可插入
pair<map<int, string>::iterator, bool> Insert_Pair;
Insert_Pair = mapStudent.insert(pair<int, string>(1, “student_one”));//其中Insert_Pair.second返回true代表插入成功 map<int, string>::iterator iter;
//迭代器遍历输出
for(iter = mapStudent.begin(); iter != mapStudent.end(); iter++)
cout<first<<’ '<second<<endl;
//逆向迭代
for(iter = mapStudent.rbegin(); iter != mapStudent.rend(); iter++)
cout<first<<" "<second<<endl;
iter = mapStudent.find(1);//查找
if(iter != mapStudent.end())
cout<<"Find, the value is "<second<<endl;
else
cout<<“Do not Find”<<endl;
mapStudent.erase(iter);//删除
//STL中默认是采用小于号来排序
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值