熟悉训练之STL容器map基础操作

//map基础操作
#include <bits/stdc++.h>
#include <iostream>
#include <cstdio>
#include <map>
using namespace std;

map<string,int>myMap;

int main()
{
    myMap["Emma"]=67;         //通过[key]的方式访问
    myMap["Benedict"]=100;
    myMap.insert(pair<string,int>("Bob",72));        //insert添加特定元素
    myMap.insert(pair<string,int>("Mary",85));
    myMap.insert(pair<string,int>("Alice",93));
    cout<<"size of myMap:"<<myMap.size()<<endl;
    cout<<"score of Benedict:"<<myMap["Benedict"]<<endl;
    cout<<"score of Mary:"<<myMap.at("Mary")<<endl;         //at()方式访问
    myMap.erase("Benedict");         //删除Benedict元素
    for(map<string,int>::iterator it=myMap.begin();it!=myMap.end();++it){      //使用迭代器访问
        cout<<"score of"<<it->first<<":"<<it->second<<endl;      //begin():返回首元素迭代器;end():映射尾元素之后一个位置的迭代器
    }
    myMap.clear();      //清空函数
    if(myMap.empty()){      //判空函数empty
        cout<<"Is empty!"<<endl;
    }else{
        cout<<"Not empty!"<<endl;
    }
    map<string,int>::iterator he=myMap.find("Bob");      //查找特定元素
    if(he!=myMap.end()){
        cout<<"Is found!"<<endl;
    }else{
        cout<<"404 Not Found"<<endl;
    }
    cout<<"size of myMap:"<<myMap.size()<<endl;
    return 0;
}
/*
size of myMap:5
score of Benedict:100
score of Mary:85
score ofAlice:93
score ofBob:72
score ofEmma:67
score ofMary:85
Is empty!
404 Not Found
size of myMap:0

Process returned 0 (0x0)   execution time : 3.237 s
Press any key to continue.
*/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值