//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.
*/
熟悉训练之STL容器map基础操作
最新推荐文章于 2022-05-16 18:15:45 发布