须知在尖括号中定义你容器里的元素类型 mapstring,int people使用前提#includemap1.特征map元素存储在键值对中Map 映射通常实现为二叉搜索树2.映射中的元素包括可通过键而不是索引访问并且每个键都是唯一的。按其键自动按升序排序。mapkeytype, valuetypemapName也就是说上面的string是keyint是value。3.声明时赋值方式eg:mapstring, int people { {John, 32}, {Adele, 45}, {Bo, 29} };4.访问方式无法通过索引访问需要通过key访问对应的value值也可以通过.at()来访问eg:#include iostream #include map using namespace std; int main() { // Create a map that will store the name and age of different people mapstring, int people { {John, 32}, {Adele, 45}, {Bo, 29} }; // Get the value associated with the key John cout John is: people[John] \n; // Get the value associated with the key Adele cout Adele is: people.at(Adele) \n; return 0; }运行结果更改值可以people[John] value,也可以people.at(John) value添加值eg:people[key] value也可以使用.insert({key,value})map中不能出现key相同的元素但是value是可以相等的5.删除元素用.erase()只用删除Key值全删可以用.cleareg:.erase(John)6.查看地图大小.size()7.查询是否为空.empty()8..count()还可以使用该函数检查是否存在特定元素。.count(key)如果元素存在则返回 true如果元素不存在则返回 falseeg:#include iostream #include map using namespace std; int main() { mapstring, int people { {John, 32}, {Adele, 45}, {Bo, 29} }; cout people.count(John)endl; cout people.count(chen); return 0; }运行结果9.遍历mapmap不同于前几个(vector,stack,set,queue,list)只储存一种类型的元素map存储一组元素可能相同也可能不同所以遍历方式也不同于其他。我们需要用auto关键字这个关键字可以自动识别元素的类型在循环中每次访问需要用.first和.second访问每个元素的key和value。、eg:#include iostream #include map using namespace std; int main() { mapstring, int people { {John, 32}, {Adele, 45}, {Bo, 29} }; for (auto pair : people) { cout pair.first is: pair.second \n; } return 0; }输出结果通过输出结果我们可以发现map自动把key给排序了默认是升序。若想在遍历输出时是按照key的降序输出可以这样定义mapstring, int,greaterstring people { {John, 32}, {Adele, 45}, {Bo, 29} };10.swap()函数将 map 的内容与 map x 的内容交换#include iostream #include map using namespace std; int main(void) { mapchar, int m1 { {a, 1}, {b, 2}, {c, 3}, {d, 4}, {e, 5}, }; mapchar, int m2; m2.swap(m1); cout Map2 contains following elements endl; for (auto it m2.begin(); it ! m2.end(); it) cout it-first it-second endl; cout Map1 contains following elements endl; for (auto it m1.begin(); it ! m1.end(); it) cout it-first it-second endl; coutm1.size(); return 0; }运行结果unordered_map无序映射是像字典一样的数据结构。 它是键值对的序列其中只有单个值与每个唯一键相关联。 它通常被称为关联数组。它可以根据它们的键快速检索单个元素。 它还实现了直接访问运算符下标运算符[]它允许使用其键值作为参数直接访问映射值。他不会按照键的值来进行排序而是根据其哈希值组织成桶以允许直接通过键值快速访问各个元素。在通过键访问单个元素时无序映射比映射执行得更好。 但是对于范围迭代它们的性能相当低。大家根据需求来选取map还是unordered_map使用注意最新学习时了解到map并不是严格按照下标来取值的比如mapint,string mymap{{1,wuhu},{2,wuhan},{3,ningbo}};可能大多数人也认为取mymap[0]的时候指的时{1“wuhu}这份值但其实是意思是找key为0的value值当然目前mymap里没有这个key值所以会打印空并当再打印一次整个mymap时会发现0已经被加入mymap里了作为新key对应的value是空可以进行赋值。这里使用时需要注意。