C++ map multimap查找删除

本文通过示例介绍了C++中map和multimap的基本用法,包括元素的插入、查找与删除操作,并展示了如何处理重复键值的情况。

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

//map multimap 查找,删除
#include<iostream>
#include<map>
#include<string>
using namespace std;
int main()
{
map<int, string> a;
multimap<int, string> ma;


a.insert(map<int, string>::value_type(1, "one"));
a.insert(map<int, string>::value_type(2, "two"));
a.insert(map<int, string>::value_type(3, "three"));
a.insert(make_pair(-1, "minus one"));
a.insert(pair<int, string>(1000, "one thousand"));
a[1000000] = "one million";


cout << "最简单的查找" << endl;
cout << a[3] << endl;//通过键值进行寻找




map<int, string>::const_iterator i;
for (i = a.begin(); i != a.end(); i++)
{
cout << "key: " << i->first;
cout << "value: " << i->second.c_str();
cout << endl;
}


ma.insert(map<int, string>::value_type(1, "one"));
ma.insert(map<int, string>::value_type(2, "two"));
ma.insert(map<int, string>::value_type(3, "three"));
ma.insert(make_pair(-1, "minus one"));
ma.insert(pair<int, string>(1000, "one thousand"));
ma.insert(pair<int, string>(1000, "one thousand"));


multimap<int, string>::const_iterator fj;
for (fj = ma.begin(); fj != ma.end(); fj++)
{
cout << "key: " << fj->first;
cout << "value: " << fj->second.c_str();
cout << endl;
}


//查找
multimap<int, string>::const_iterator fi;
fi = ma.find(1000);
if (fi != ma.end())
{
cout << "找到了1000" << endl;
size_t n = ma.count(1000);
for (size_t i = 0; i < n; i++)
{
cout << "\t key: " << fi->first;
cout << ",value: " << fi->second;
fi++;
}
}
//删除
if (ma.erase(-1) > 0)//通过键值进行删除
{
cout << endl << "删除-1成功!" << endl;
}
//先查找再删除
multimap<int, string>::iterator fk = ma.find(45);
if (fk != ma.end())
{
ma.erase(fk);
cout << "删除成功" << endl;
}
//删除范围
ma.erase(ma.lower_bound(1000), ma.upper_bound(1000));
system("pause");
return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值