C++语法基础--关联容器--map(二)--查找并读取map中的元素count(),find()与 从map对象中删除元素erase()

来源:互联网 发布:mac做java开发工具 编辑:程序博客网 时间:2024/05/18 22:45
1.查找并读取map中的元素count(),find()
    

 *对于map对象,count成员的返回值只能是0或1
  原型:
        iterator find (const key_type& k);
  const_iterator find (const key_type& k) const
  size_type count (const key_type& k) const;

eg:
   int main ()
   {
    map<string,int> mymap;
    map<string,int>::iterator it;
    mymap["jack"]=18;

    cout<<mymap["rose"]<<endl;  //直接使用下标的弊端:mymap并不存在"rose"的键,

                                                           //但是却把"rose"插入了mymap

if(mymap.count("tom"))         //mymap并不存在"tom"的键,返回0
{
cout<<mymap["tom"]<<endl;;
}
it=mymap.find("jack"); //返回"jack"在mymap中的迭代器
cout<<it->first<<": "<<it->second<<endl;  //验证返回的迭代器
       mymap.find("lily");   //mymap并不存在"lily"的键,返回end()迭代器,但并不会插入"lily"的键值                     
   
for(it=mymap.begin();it!=mymap.end();it++)
{
 cout<<it->first<<": "<<it->second<<endl;
}


  return 0;
}


 运行结果:
     




2. 从map对象中删除元素
       

   原型:
     void erase (iterator position);
size_type erase (const key_type& k);
void erase (iterator first, iterator last);

  eg:
      int main ()
   {
    map<string,int> mymap;
    map<string,int>::iterator it;
    mymap["jack"]=18;
mymap["tom"]=19;
mymap["jany"]=17;
mymap["rose"]=20;
mymap["lily"]=16;
cout<<"before erase: "<<endl;
for (it=mymap.begin(); it!=mymap.end(); ++it)
       {
 cout << it->first << " => " << it->second << '\n';
 }


it=mymap.find("tom");
        mymap.erase (it);                   
// erasing by iterator
        mymap.erase ("rose");                  // erasing by key
        it=mymap.find ("jany");
        mymap.erase ( it, mymap.end() );    // erasing by range
cout<<"after erase: "<<endl;
 for (it=mymap.begin(); it!=mymap.end(); ++it)
         {
 cout << it->first << " => " << it->second << '\n';
 }


        return 0;
     }
  运行结果:
   
原创粉丝点击