简述
- map的所有元素都是Pair,Pair中第一个元素是key,第二个元素是value
- map中所有元素都会根据元素的键值自动排序,可以通过key快速找到value
- map中的key是不允许重复的,如果需要一个可以重复的map,可以改用multimap
基本应用
#include <iostream>
#include <string>
#include <map>
using namespace std;
int main()
{
//创建
map<int,int> m;
map<int,int> m2(m);//拷贝构造函数,拷贝m
map<int, int> m3;
m3 = m;//赋值,其实本质也是拷贝构造函数
map<int, int> m4;
m4.swap(m);//m4和m实现数据互换
//增
m.insert(pair<int,int>(1,10));//插入一个键值对,key为1.value为10
m.insert(pair<int,int>(2,20));//插入一个键值对,key为2.value为20
m.insert(pair<int,int>(3,30));//插入一个键值对,key为3.value为30
//大小
cout <<"元素数量为:"<< m.size() << endl;
cout <<"map是否为空:"<< m.empty() << endl;
//改
map<int, int>::iterator it2 = m.find(1);
it2->second = 100;
//遍历
for (map<int, int>::iterator it = m.begin(); it != m.end();it++){
cout << "key:" << it->first << ",value:" << it->second << endl;
};
//查
map<int, int>::iterator it = m.find(5);//如果找到了则返回该键的迭代器,如果不存在,则返回end()
cout << "map中是否存在key为5的值:" <<(it != m.end())<< endl;
cout << "map中key为1的元素的数量:" <<m.count(1)<< endl;
//删
m.erase(m.begin());//删除迭代器指定的元素
m.erase(m.begin(), m.end());//删除指定区间的元素
m.erase(1);//删除key为1的元素
m.clear();//清空map
return 0;
}
Map排序
using namespace std;
int main()
{
//创建
map
//增
m.insert(pair<int,int>(2,20));
m.insert(pair<int,int>(3,30));
m.insert(pair<int,int>(1,10));
//遍历
for (map<int, int>::iterator it = m.begin(); it != m.end();it++){
cout << "key:" << it->first << ",value:" << it->second << endl;
};
return 0;
}
> key:1,value:10
> key:2,value:20
> key:3,value:30
- 自定义排序
```cpp
#include <iostream>
#include <string>
#include <map>
using namespace std;
class MyCompare{
public:
bool operator()(int v1,int v2){
return v1 > v2;
}
};
int main()
{
//创建
map<int,int,MyCompare> m;
//增
m.insert(pair<int,int>(2,20));
m.insert(pair<int,int>(3,30));
m.insert(pair<int,int>(1,10));
//遍历
for (map<int, int>::iterator it = m.begin(); it != m.end();it++){
cout << "key:" << it->first << ",value:" << it->second << endl;
};
return 0;
}
key:3,value:30 key:2,value:20 key:1,value:10