【工作中学习2】Map的使用及排序(第三个参数)

  项目进行中,使用到Map(std::map),Map要点整理如下:

  1. Map,也叫关联数组,提供key/value(键/值对),key用来索引,value是被存储和检索的数据。

  2. key值唯一(Multimap除外)。

  3. Map的内部数据结构是红黑树

  3. 可以用下标操作符,添加Map中的数据,例如map[1] = 2;,用下标操作符查找数据时,如果数据不存在,会被自动插入到Map中。

  4. Map中的数据默认按照由key从小到大排序(less),可以修改第三个参数(可选)来修改排序法则。

 

  程序举例:

 1 // testMap.cpp : Defines the entry point for the console application.
 2 //
 3 
 4 #include "stdafx.h"
 5 #include <string>
 6 #include <map>
 7 #include <iostream>
 8 
 9 struct SortMap  
10 {
11     bool operator ()( const int i1, const int i2 )  
12     {  
13         return i1 > i2;  
14     }  
15 };
16 
17 //traverse the map
18 void traverseMap(const std::map<int, std::string>& map)
19 {
20     std::map<int, std::string>::const_iterator iter = map.begin();
21     
22     while(iter != map.end())
23     {
24         std::cout << "" << iter->first << "," << iter->second << std::endl;
25         iter++;
26      }
27 }
28 
29 void traverseSortMap(const std::map<int, std::string, SortMap>& map)
30 {
31     std::map<int, std::string, SortMap>::const_iterator iter = map.begin();
32 
33     while(iter != map.end())
34     {
35         std::cout << "" << iter->first << "," << iter->second << std::endl;
36         iter++;
37     }
38 }
39 
40 
41 int _tmain(int argc, _TCHAR* argv[])
42 {
43     std::map<int, std::string> map1;
44     map1[1] = "no";
45     map1[6] = "hi";
46     map1[5] = "me";
47     map1[9] = "ok";
48     
49     traverseMap(map1);
50     std::cout << "-------------------------------------------" << std::endl;
51     
52     std::map<int, std::string, SortMap> map2;
53     map2[1] = "no";
54     map2[6] = "hi";
55     map2[5] = "me";
56     map2[9] = "ok";
57     
58     traverseSortMap(map2);
59     
60     system("pause");
61     return 0;
62 }

  

  运行结果:

  

 

  继续努力~

转载于:https://www.cnblogs.com/KevinSong/p/3725133.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值