STL之map&multimap使用简介

map

1.insert

第一种:用insert函数插入pair数据
#include <map>
#include <string>
#include <iostream>
using namespace std;
int main()
{
       map<int, string> map;
       map.insert(pair<int, string>(1, “one”));
       map.insert(pair<int, string>(2, “two”));
       map.insert(pair<int, string>(3, “three”));
       map<int, string>::iterator  iter;
       for(iter = map.begin(); iter != map.end(); iter++)
        {
          cout<<iter->first<<”   ”<<iter->second<<end;
        }
}    
第二种:用insert函数插入value_type数据
#include <map>
#include <string>
#include <iostream>
using namespace std;
int main()
{
       map<int, string> map;
       map.insert(map<int, string>::value_type (1, “one”));
       map.insert(map<int, string>::value_type (2, “two”));
       map.insert(map<int, string>::value_type (3, “three”));
       map<int, string>::iterator  iter;
       for(iter = map.begin(); iter != map.end(); iter++)
        {
          cout<<iter->first<<”   ”<<iter->second<<end;
        }
}   
第三种:用数组方式插入数据
#include <map>
#include <string>
#include <iostream>
using namespace std;
int main()
{
       map<int, string> map;
       map[1]=“one”;
       map[2]=“two”;
       map[3]= “three”;
       map<int, string>::iterator  iter;
       for(iter = map.begin(); iter != map.end(); iter++)
        {
          cout<<iter->first<<”   ”<<iter->second<<end;
        }
}   

map 总是以(key,value)的形式存在,当插入的数据的key已经存在时,会形成覆盖,map内部使用红黑树实现。

 

2.size
返回map的大小
 
3.遍历
  可以使用迭代器方式,如1中的例子
  也可以使用[],但是注意索引从1开始
 
#include <map>
#include <string>
#include <iostream>
using namespace std;
int main()
{
       map<int, string> map;
       map.insert(pair<int, string>(1, “one”));
       map.insert(pair<int, string>(2, “two”));
       map.insert(pair<int, string>(3, “three”));
       for(int index=1;index<=map.size();index++)
        {
          cout<<map[index]<<endl;
        }
}    

 

4.查找

map.find()如果查找到,返回指向结果的迭代器,如果没有找到到,返回map.end()

 

5.上下界

lower_bound函数用法,这个函数用来返回要查找关键字的下界(是一个迭代器),返回键值>=给定元素的第一个位置
upper_bound函数用法,这个函数用来返回要查找关键字的上界(是一个迭代器),返回键值>给定元素的第一个位置

 

6.清空与判空

清空map中的数据可以用clear()函数,判定map中是否有数据可以用empty()函数,它返回true则说明是空map
 
multimap和map的区别在于,multimap允许key重复,其他没啥特别的地方,底层也是红黑树实现

转载于:https://www.cnblogs.com/tla001/p/6642790.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值