首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【工作中学习2】Map的使用及排序(第三个参数)

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

作者头像
宋凯伦
发布2018-01-04 14:25:33
8620
发布2018-01-04 14:25:33
举报

  项目进行中,使用到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 }

  运行结果:

  继续努力~

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2014-05-13 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档