[c++] <Map>

特性

  • map<K, T>:保存 pair<const K, T> 类型元素,元素顺序通过比较键的值确认
  • pair<const K, T>:封装了键(K)和值(T),键的值唯一,对象的值可重复
  • multimap<K, T>:键的值可以重复
  • unordered_map<K, T>:pair<const K, T>元素的顺序不是直接由键的值确定,而是由键的值的哈希值确定,键的值唯一
  • unordered_multimap<K, T>:键的值可以重复

函数

  • begin():返回指向map头部的迭代器
  • end():返回指向map末尾的迭代器
  • find():查找一个元素
  • erase():删除一个元素
  • empty():如果map为空则返回true
  • insert():插入元素
  • size():返回map中元素的个数
  • lower_bound():返回键值>=给定元素的第一个位置
  • upper_bound():返回键值>给定元素的第一个位置

示例

 1 #include <iostream>
 2 #include <string> 
 3 #include <map>
 4 using namespace std;
 5 
 6 int main(){
 7     map<int, string> mapStudent;
 8     mapStudent.insert(pair<int,string>(1,"stu_1"));
 9     mapStudent.insert(pair<int,string>(2,"stu_2"));
10     mapStudent.insert(pair<int,string>(3,"stu_3"));
11     
12     map<int,string>::iterator iter;
13     iter = mapStudent.find(1);
14     if(iter != mapStudent.end())
15         cout<<"Find, the value is"<<iter->second<<endl;
16     else
17         cout<<"Do not Find"<<endl;
18     return 0;
19 }
View Code

参考

c++ 容器函数详解

https://zouzhongliang.com/index.php/c-biaozhunmobankustlgehanshuxiangjie/

C++中的STL中map用法详解

https://www.cnblogs.com/fnlingnzb-learner/p/5833051.html

原文地址:https://www.cnblogs.com/cxc1357/p/12625599.html