简述

  • map的所有元素都是Pair,Pair中第一个元素是key,第二个元素是value
  • map中所有元素都会根据元素的键值自动排序,可以通过key快速找到value
  • map中的key是不允许重复的,如果需要一个可以重复的map,可以改用multimap

基本应用

  1. #include <iostream>
  2. #include <string>
  3. #include <map>
  4. using namespace std;
  5. int main()
  6. {
  7. //创建
  8. map<int,int> m;
  9. map<int,int> m2(m);//拷贝构造函数,拷贝m
  10. map<int, int> m3;
  11. m3 = m;//赋值,其实本质也是拷贝构造函数
  12. map<int, int> m4;
  13. m4.swap(m);//m4和m实现数据互换
  14. //增
  15. m.insert(pair<int,int>(1,10));//插入一个键值对,key为1.value为10
  16. m.insert(pair<int,int>(2,20));//插入一个键值对,key为2.value为20
  17. m.insert(pair<int,int>(3,30));//插入一个键值对,key为3.value为30
  18. //大小
  19. cout <<"元素数量为:"<< m.size() << endl;
  20. cout <<"map是否为空:"<< m.empty() << endl;
  21. //改
  22. map<int, int>::iterator it2 = m.find(1);
  23. it2->second = 100;
  24. //遍历
  25. for (map<int, int>::iterator it = m.begin(); it != m.end();it++){
  26. cout << "key:" << it->first << ",value:" << it->second << endl;
  27. };
  28. //查
  29. map<int, int>::iterator it = m.find(5);//如果找到了则返回该键的迭代器,如果不存在,则返回end()
  30. cout << "map中是否存在key为5的值:" <<(it != m.end())<< endl;
  31. cout << "map中key为1的元素的数量:" <<m.count(1)<< endl;
  32. //删
  33. m.erase(m.begin());//删除迭代器指定的元素
  34. m.erase(m.begin(), m.end());//删除指定区间的元素
  35. m.erase(1);//删除key为1的元素
  36. m.clear();//清空map
  37. return 0;
  38. }

Map排序

  • 默认排序 ```cpp

    include

    include

    include

using namespace std;

int main() { //创建 map m;

  1. //增
  2. m.insert(pair<int,int>(2,20));
  3. m.insert(pair<int,int>(3,30));
  4. m.insert(pair<int,int>(1,10));
  5. //遍历
  6. for (map<int, int>::iterator it = m.begin(); it != m.end();it++){
  7. cout << "key:" << it->first << ",value:" << it->second << endl;
  8. };
  9. return 0;

}

  1. > key:1,value:10
  2. > key:2,value:20
  3. > key:3,value:30
  4. - 自定义排序
  5. ```cpp
  6. #include <iostream>
  7. #include <string>
  8. #include <map>
  9. using namespace std;
  10. class MyCompare{
  11. public:
  12. bool operator()(int v1,int v2){
  13. return v1 > v2;
  14. }
  15. };
  16. int main()
  17. {
  18. //创建
  19. map<int,int,MyCompare> m;
  20. //增
  21. m.insert(pair<int,int>(2,20));
  22. m.insert(pair<int,int>(3,30));
  23. m.insert(pair<int,int>(1,10));
  24. //遍历
  25. for (map<int, int>::iterator it = m.begin(); it != m.end();it++){
  26. cout << "key:" << it->first << ",value:" << it->second << endl;
  27. };
  28. return 0;
  29. }

key:3,value:30 key:2,value:20 key:1,value:10