• 【工作中学习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 }

      

      运行结果:

      

      继续努力~

  • 相关阅读:
    二分法查找(C语言)
    冒泡排序法(C语言)
    Python 字符串操作方法大全
    guns搭建笔记
    mysql数据库下载及安装
    docker安装
    自动化学习路径及问题汇总目录
    UI自动化使用docker做并行执行
    allure趋势图无数据
    allure报告不显示@Attachment
  • 原文地址:https://www.cnblogs.com/KevinSong/p/3725133.html
Copyright © 2020-2023  润新知