标准库类型之map

  • 使用map得包含map类所在的头文件
    #include <map> 
  • 定义一个map对象:
    map<string, int> mapTest;//用string作为索引,存储int对象

【四种方法】

  • mapTest["aaa"] = 100;
  • mapTest.insert(map<string, int>::value_type("bbb", 200));
  • mapTest.insert(pair<string, int>("ddd", 400));
  • mapTest.insert(make_pair<string, int>("ccc", 300));

 

编译运行:

如果先插入500那输出会有影响么?

可见它默认是按照key从小到大的顺序排列的。正因为如此,所以map中的key是有要求的:一定得重载<号运算符,另外我们是可以人为改变map默认的排序规则的,JAVA中也有类似的,关于如何自定义排序等将来学习STL再来探究。

如果插入的key的值重复了又该如何呢?

结果:

那其它的插入方式如果key重复了也是保留最后一次么?下面来试试:

结果:

  • mapTest["aaa"] = 100;
  • map<string, int>::iterator it = mapTest.find(“aaa”);
  • it->second = 666;

如果查找一个不存在的呢?

结果:

编译运行:

如果说没有找到呢?

  •  mapTest.erase(“aaa”);
  • mapTest.erase(it);

原文地址:https://www.cnblogs.com/webor2006/p/5495383.html