当前位置:   article > 正文

【STL】map中find的用法、map的insert插入:pair make_pair_insert make pair

insert make pair

用find函数来定位数据出现位置,它返回的一个迭代器,当数据出现时,它返回数据所在位置的迭代器,如果map中没有要查找的数据,它返回的迭代器等于end函数返回的迭代器,程序说明

#include <map>

#include <string>

#include <iostream>

Using namespace std;

Int main()

{

       Map<int, string> mapStudent;

       mapStudent.insert(pair<int, string>(1, “student_one”));

       mapStudent.insert(pair<int, string>(2, “student_two”));

       mapStudent.insert(pair<int, string>(3, “student_three”));

       map<int, string>::iterator iter;

       iter = mapStudent.find(1);

if(iter != mapStudent.end())

{

       Cout<<”Find, the value is ”<<iter->second<<endl;

}

Else

{

       Cout<<”Do not Find”<<endl;

}

}

 

二、map表插入键值对时有两种方法:

  1. map<int,int> m;
  2. m.insert(make_pair(3,4));
  3. m.insert(pair<int,int>(1,3));
  4. map<int,int>::iterator it = m.begin();
  5. while(it != m.end())
  6. {
  7. cout<<"it->first : "<<it->first<<" it->second : "<<it->second<<endl;
  8. it++;
  9. }

注意:pair是类模板,所以需要模板参数列表,而make_pair是函数,则不需要。

三、map的遍历 

用迭代器遍历:则根据key的有序遍历

用key值遍历:是在已知key的基础上

  1. map<char,int> m;
  2. int value = 1;
  3. for(char i = 'a';i <= 'z';i++)
  4. {
  5. m.insert(pair<char,int>(i,value++));
  6. }
  7. //利用key值 直接找到value
  8. for(char i = 'a';i <= 'z';i++)
  9. {
  10. cout<<i<<" : "<<m[i]<<endl;
  11. }

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/运维做开发/article/detail/992050
推荐阅读
相关标签
  

闽ICP备14008679号