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

时间:2023-03-09 22:00:21
【工作中学习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),可以修改第三个参数(可选)来修改排序法则。

  程序举例:

 // testMap.cpp : Defines the entry point for the console application.
// #include "stdafx.h"
#include <string>
#include <map>
#include <iostream> struct SortMap
{
bool operator ()( const int i1, const int i2 )
{
return i1 > i2;
}
}; //traverse the map
void traverseMap(const std::map<int, std::string>& map)
{
std::map<int, std::string>::const_iterator iter = map.begin(); while(iter != map.end())
{
std::cout << "" << iter->first << "," << iter->second << std::endl;
iter++;
}
} void traverseSortMap(const std::map<int, std::string, SortMap>& map)
{
std::map<int, std::string, SortMap>::const_iterator iter = map.begin(); while(iter != map.end())
{
std::cout << "" << iter->first << "," << iter->second << std::endl;
iter++;
}
} int _tmain(int argc, _TCHAR* argv[])
{
std::map<int, std::string> map1;
map1[] = "no";
map1[] = "hi";
map1[] = "me";
map1[] = "ok"; traverseMap(map1);
std::cout << "-------------------------------------------" << std::endl; std::map<int, std::string, SortMap> map2;
map2[] = "no";
map2[] = "hi";
map2[] = "me";
map2[] = "ok"; traverseSortMap(map2); system("pause");
return ;
}

  

  运行结果:

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

  继续努力~