#include <map>
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
struct Display
{
void operator()(pair<string,double> info)
{
cout << info.first << ":" << info.second << endl;
}
};
int main(){
map<string, double> scores;
//map的插入
scores["jack"] = 98.9;
scores["xiaoming"] = 90.2;
scores["lisi"] = 95.1;
scores["wangwu"] = 86.1;
scores.insert(pair<string, double>("zhangsan", 100.0 )); //这样也可以插入元素
//使用for_each遍历
for_each(scores.begin(), scores.end(), Display());
//使用迭代器查找
map<string,double>::iterator iter;
iter = scores.find("lisi");
if(iter != scores.end())
{
cout << "Found the score is " << iter->second << endl;
}
else
{
cout << "Didn't find the key." << endl;
}
//使用迭代器完成遍历
for(iter = scores.begin(); iter!=scores.end();iter++)
{
cout << iter->second << endl;
}
//把scores值小于90的键值对删除
for(iter = scores.begin(); iter!=scores.end();iter++)
{
if(iter->second < 90)
{
iter = scores.erase(iter);//erase会返回当前iter的下一个iter
}
}
for_each(scores.begin(), scores.end(), Display());
cout << "-------" << endl;
//删除元素的另一种方法,通过find查找,再删除
iter = scores.find("xiaoming");
scores.erase(iter);
for_each(scores.begin(), scores.end(), Display());
cout << "-------" << endl;
//另一种删除元素的方法,若返回不为0,表示删除了,若返回为0,表示没有找到
int n = scores.erase("lisi");
cout << n << endl;
//清空map容器
scores.erase(scores.begin(), scores.end());
return 0;
}
C++中的map容器的删除、插入、遍历
最新推荐文章于 2023-10-21 13:03:27 发布