STL map 详细用法

快来打我* 2021-10-30 04:44 551阅读 0赞

Map是STL的一个关联容器,它提供一对一(其中第一个可以称为关键字,每个关键字只能在map中出现一次,第二个称为该关键字的值)的数据 处理能力。

需要的库

  1. #include <map>

基本操作

定义

  1. map<string,int>m;

这是定义了一个以string为关键字,以int为值的map

插入

方法1:

  1. map<string,int>m;
  2. m["Bob"]=101;
  3. m["Alice"]=102;
  4. m["Eric"]=103;

方法2:

  1. m.insert(pair<string,int>("Lee",104));

方法3:

  1. m.insert(map<string,int>::value_type("Karen",105));

遍历

定义一个迭代指针iter,使其指向map,实现对map的遍历。

  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. int main()
  4. {
  5. map<string,int>m;
  6. m["Bob"]=101;
  7. m["Alice"]=102;
  8. m["Eric"]=103;
  9. map<string,int>::iterator iter;
  10. for(iter=m.begin(); iter!=m.end(); iter++)
  11. cout<<iter->first <<"->"<<iter->second<<endl;
  12. }

输出为:

  1. Alice->102
  2. Bob->101
  3. Eric->103

可以看到map自动在内部以关键字为准,按字典序排序,而不是根据输入的顺序;

需要注意的是 当我进行实验的时候 我发现这样一个现象:

  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. int main()
  4. {
  5. map<string,int>m;
  6. m["Bob"]=101;
  7. m["Alice"]=102;
  8. m["Eric"]=103;
  9. map<string,int>::iterator iter;
  10. for(iter=m.begin(); iter!=m.end(); iter++)
  11. cout<<iter->first <<"->"<<iter->second<<endl;
  12. if(m["AAA"]==0)
  13. cout<<"NO"<<endl;
  14. for(iter=m.begin(); iter!=m.end(); iter++)
  15. cout<<iter->first <<"->"<<iter->second<<endl;
  16. }

当询问一个map中不存在的数的时候,返回的值应该是0,不过当你再次遍历的时候,就会发现map中已经多了一个键值对,只不过值是0:

  1. Alice->102
  2. Bob->101
  3. Eric->103
  4. NO
  5. AAA->0
  6. Alice->102
  7. Bob->101
  8. Eric->103

在做题时一定要好好注意。

查找

方法1:

  1. cout<<m.find("Bob")->second<<endl;

如果按关键字搜索,搜不到的话会输出乱码

方法2:

  1. map<string,int>::iterator iter1;
  2. iter1 = m.find(string("Bob"));
  3. if(iter1 != m.end())
  4. cout<<iter1->first <<"->"<<iter1->second<<endl;
  5. else
  6. cout<<"no fount"<<endl;

定义一个指针,指向map,如果没有的话会返回m.end()

删除

方法1

  1. m.erase(iter1);

同样的是指针的操作

方法2

  1. m.erase(string("AAA"));

或者是根据关键字删除

map的相关函数

  • begin() 返回指向map头部的迭代器
  • clear() 删除所有元素
  • count() 返回指定元素出现的次数
  • empty() 如果map为空则返回true
  • end() 返回指向map末尾的迭代器
  • equal_range() 返回特殊条目的迭代器对
  • erase() 删除一个元素
  • find() 查找一个元素
  • get_allocator() 返回map的配置器
  • insert() 插入元素
  • key_comp() 返回比较元素key的函数
  • lower_bound() 返回键值>=给定元素的第一个位置
  • max_size() 返回可以容纳的最大元素个数
  • rbegin() 返回一个指向map尾部的逆向迭代器
  • rend() 返回一个指向map头部的逆向迭代器
  • size() 返回map中元素的个数
  • swap() 交换两个map
  • upper_bound() 返回键值>给定元素的第一个位置
  • value_comp() 返回比较元素value的函数

转载于:https://www.cnblogs.com/dyhaohaoxuexi/p/11257335.html

发表评论

表情:
评论列表 (有 0 条评论,551人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Map

    写在前面:今天被一个问题困扰了大半天,晚上还是没能解决于是索性关好电脑决定回宿舍放松放松暂时放弃。回来的路上突然就想到了可能导致问题的原因所在,于是一回宿舍就打开电脑上网查了资

    相关 map详细

    map的详细用法:       map是STL的一个关联容器,它提供一对一(其中第一个可以称为关键字,每个关键字只能在map中出现一次,第二个可能称为该关键字的值)的

    相关 STL详细

    需要头文件 \include<algorithm> using namespace std;   这个函数可以传两个参数或三个参数。第一个参数是要排序的区间首地址,第二

    相关 STL map 详细

    Map是STL的一个关联容器,它提供一对一(其中第一个可以称为关键字,每个关键字只能在map中出现一次,第二个称为该关键字的值)的数据 处理能力。 需要的库 i