STL:map用法总结

一、简介

Map是STL中一对一的关联容器,其中第一个称为key,Map中的key是唯一的;第二个称为Map的value。Map内部自建一颗红黑树,这棵树内部具有自动排序的功能(key是有序的)。使用时需要引入头文件:#include <map>.对于迭代器来说,可以修改实值,而不能修改key。根据key值快速查找记录,查找的复杂度基本是log(n);

二、map的基本操作

begin()         返回指向map头部的迭代器
end()           返回指向map末尾的迭代器
rbegin()        返回一个指向map尾部的逆向迭代器
rend()          返回一个指向map头部的逆向迭代器
lower_bound()   返回键值>=给定元素的第一个位置
upper_bound()    返回键值>给定元素的第一个位置
insert()        插入元素
clear()        删除所有元素
size()          返回map中元素的个数
swap()           交换两个map。map中的swap不是一个容器中的元素交换,而是两个容器所有元素的交换。
count()         返回指定元素出现的次数
empty()         如果map为空则返回true
equal_range()   返回特殊条目的迭代器对
erase()         删除一个元素
find()          查找一个元素
get_allocator() 返回map的配置器
key_comp()      返回比较元素key的函数
value_comp()     返回比较元素value的函数
max_size()      返回可以容纳的最大元素个数

三、插入数据

第一种:用insert函数插入pair数据

#include <map>  
#include <string>  
#include <iostream>  
using namespace std;  
int main()  
{  
    map<int, string> mapStudent;  
    mapStudent.insert(pair<int, string>(1, "student_one"));  
    mapStudent.insert(pair<int, string>(2, "student_two"));  
    mapStudent.insert(pair<int, string>(3, "student_three"));  
    map<int, string>::iterator iter;  
    for(iter = mapStudent.begin(); iter != mapStudent.end(); iter++)  
       cout<<iter->first<<' '<<iter->second<<endl;  
}  

第二种:用insert函数插入value_type数据

#include <map>  
#include <string>   
#include <iostream>  
using namespace std;  
int main()  
{  
  
    map<int, string> mapStudent;  
    mapStudent.insert(map<int, string>::value_type (1, "student_one"));  
    mapStudent.insert(map<int, string>::value_type (2, "student_two"));  
    mapStudent.insert(map<int, string>::value_type (3, "student_three"));  
    map<int, string>::iterator iter;  
    for(iter = mapStudent.begin(); iter != mapStudent.end(); iter++)  
       cout<<iter->first<<' '<<iter->second<<endl;  
} 

第三种:用数组方式插入数据

#include <map>  
#include <string>  
#include <iostream>  
using namespace std;  
int main()  
{  
    map<int, string> mapStudent;  
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值