STL学习(一)map容器学习(二)

本文详细介绍了如何使用C++ STL中的map容器进行元素插入、查找、迭代及删除等基本操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <map> 
#include <iostream>

int main( ) 
{ 
   using namespace std; 
   
   
   map<string,int> person;
   
   person.insert(make_pair("strength",200));
   
   pair<map<string, int>::iterator, bool> ret = person.insert(make_pair("strength",100));
   
   cout << "ret : " << ret.second << endl;
   person.insert(make_pair("defence",50));
   person.insert(make_pair("magic",10));
   person.insert(make_pair("crtical strike",5));
   person.insert(make_pair("crtical strike",20));
   
   map<string,int>::iterator iter;
   map<string,int>::iterator iter2;
   iter = person.find("crtical strike");

   cout << "crtical strike is " << iter->second << endl;   

   iter = person.begin();
    
   iter2 = person.insert(person.end(),make_pair("health",30));
   cout<<endl; 
   cout << "iter2 : " << iter2->first<< " : " << iter2->second << endl;
   

   cout<<endl; 
   for(;iter!= person.end();iter++)
   {
     cout << iter-> first << " : " << iter->second << endl;
   }

   cout<<endl;
   cout << "Erase" << endl;
   int count = person.erase("health");

   if(count == 1)
   {
     cout << "health is erased" << endl;
   }   
   else
   {
     cout << "can't find health" << endl;
   }
   

   
   iter = person.begin();
   
   for(;iter!= person.end();iter++)
   {
     if(iter->first == "magic")
     {
        cout << "find magic!" << endl;
        break;
     }
   }

   
   person.erase(iter);
   
   iter = person.begin();

   cout << "****************list of person:**************" << endl;
   for(;iter!= person.end();iter++)
   {
     cout << iter-> first << " : " << iter->second << endl;
   }

   cout << endl;

   cout << "erase all" << endl;

  map<string,int>::iterator erase_begin = person.begin();
  map<string,int>::iterator erase_end = person.end();

  person.erase(erase_begin,erase_end);

  cout << "person size is " << person.size() << endl;
  
   
   return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值