Fork me on GitHub

STL——容器(Map & multimap)的排序与遍历

1. Map & multimap 的排序与遍历

  • map<T1,T2,less<T1> >  mapA;    //该容器是按键的升序方式排列元素。如果未指定less<T1> 函数对象,默认采用less<T1>函数对象。
  • map<T1,T2,greater<T1>> mapB;   //该容器是按键的降序方式排列元素。
  • less<T1> 与 greater<T1>    可以替换成其它的函数对象functor。
  • 可编写自定义函数 对象以进行自定义类型的比较,使用方法与set构造时所用的函数对象一样。

示例代码:

 1 #include <iostream>
 2 #include <map>
 3 
 4 using namespace std;
 5 
 6 int main()
 7 {
 8     map<int, string> mapStu1;    //默认为升序,与  map<int, string, less<int>> mapStu1; 同效
 9 
10     mapStu1.insert(pair<int, string>(1, "内容A"));
11     mapStu1.insert(pair<int, string>(2, "内容B"));
12     mapStu1.insert(pair<int, string>(3, "内容C"));
13 
14     for (map<int, string>::iterator it = mapStu1.begin(); it != mapStu1.end(); it++)        //map的遍历
15     {
16         cout << "mapStu1的第 " << it->first << "个参数为: " << it->second <<endl;
17     }
18 
19     cout << endl;
20 
21     map<int, string, greater<int>> mapStu2;        //按键的降序方式排列元素
22 
23     mapStu2.insert(pair<int, string>(1, "内容A"));
24     mapStu2.insert(pair<int, string>(2, "内容B"));
25     mapStu2.insert(pair<int, string>(3, "内容C"));
26 
27     for (map<int, string>::iterator it = mapStu2.begin(); it != mapStu2.end(); it++)
28     {
29         cout << "mapStu2的第 " << it->first << "个参数为: " << it->second << endl;
30     }
31     
32     return 0;
33 }

打印结果:

 

  

 

 

==========================================================================================================================

posted @ 2020-06-14 23:05  索智源  阅读(1653)  评论(0编辑  收藏  举报