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