- map基本概念
- 什么是map?
map是一种关联型容器。map中的元素是按照key-value的方式存储的。也就是说一个map元素包含两个值。且map排序的规则是按key的大小来排序的。 - map的功能&特点
- 输入无序,输出按key排序。
- 不能通过iterator去修改map中元素的值,因为这样会破坏排序规则。
- multimap和map的区别在于:multimap允许出现重复key值。
- map的实现原理
map跟set容器一样,底层都是用RB-tree实现的。
- 什么是map?
map常用API
初始化
map<int,int> m1; map<int,int> m2(m1); map<int,int> m3=m2;
赋值
map<int,int> m1; m1.insert(make_pair(1,2)); map<int,int> m2; m2=m1; m2[2]=9;//数组法 cout<<m2.at(2)<<endl;//at方法 map<int,int>::iterator i=m2.begin(); while(i!=m2.end()){ cout<<"the first element is:"<<i->first<<"the second element is:"<<i->second<<endl; i++; } cout<<endl;
- 元素访问
使用迭代器
数组法
at方法 大小
//size() //empty()
插入删除
插入://insert(pair<T,T>(ele,ele)) //insert(make_pair(ele,ele)) //insert(map<T,T>::value_type(ele,ele)) #include <iostream> #include <map> #include <algorithm> using namespace std; int main(){ map<int, int> m1; m1.insert(make_pair(1, 2)); m1.insert(pair<int,int>(3,4)); m1.insert(map<int, int>::value_type(5, 6)); map<int, int>::iterator i = m1.begin(); while (i != m1.end()){ cout << "the first element is: " << i->first << " the second element is: " << i->second << endl; i++; } return 0; }
删除:
//erase(iter_pos) //erase(iter_start,iter_end) //erase(ele) //clear() #include <iostream> #include <map> #include <algorithm> using namespace std; void printmap(map<int, int> &m1){ map<int, int>::iterator i = m1.begin(); while (i != m1.end()){ cout << "the first element is: " << i->first << " the second element is: " << i->second << endl; i++; } } int main(){ map<int, int> m1; m1.insert(make_pair(1, 2)); m1.insert(pair<int,int>(3,4)); m1.insert(map<int, int>::value_type(5, 6)); m1.insert(make_pair(10, 20)); m1.insert(pair<int, int>(30, 40)); m1.insert(map<int, int>::value_type(40, 50)); printmap(m1); cout << "------------------" << endl; m1.erase(m1.begin()); printmap(m1); cout << "------------------" << endl; m1.erase(10); printmap(m1); m1.erase(m1.begin(), m1.end());//相当于clear() cout << m1.size() << endl; return 0; }
查找
//find iter or .end() //lower_bound >= //upper_bound > //equal_range pairii
- multimap案例