要使用multimap必须要添加头文件#include <map>;
multimap 对象创建,元素插入
可以重复插入元素,插入元素需要使用insert()方法,下例程序重复插入了名为“Jack”的键值:
运行结果为:
Jack 300.5
Jack 306
Kity 200
Memi 500
The Code Follows:
#include <iostream>
#include <map>
using namespace std;
int main()
{
//定义map对象,当前没有任何元素;
multimap <string, double> mp;
//插入元素;
mp.insert(pair<string, double>("Jack", 300.5));
mp.insert(pair<string, double>("Kity", 200));
mp.insert(pair<string, double>("Memi", 500));
//重复插入键值"Jack";
mp.insert(pair<string, double>("Jack", 306));
//使用前向迭代器中序遍历multimap;
multimap <string, double>:: iterator it;
for(it=mp.begin(); it != mp.end(); it++) {
cout << (*it).first << " " << (*it).second << endl;
}
return 0;
}
multimap元素的删除
删除操作采用erase()方法,可删除某个迭代器位置上的元素,等于某个键值的所有重复元素,一个迭代器区间上的元素,使用clear()方法可将multimap容器内的元素清空;
因为有重复的键值,所以,删除操作会将要删除的键值一次性从multimap中删除。请看下例程序:
运行结果为:
The elements before deleted :
Jack 300.5
Jack 306
Kity 200
Memi 500
The elements after deleted :
Kity 200
Memi 500
The Code Follows:
#include <iostream>
#include <map>
using namespace std;
int main()
{
//定义map对象,当前没有任何元素;
multimap <string, double> mp;
//插入元素;
mp.insert(pair<string, double>("Jack", 300.5));
mp.insert(pair<string, double>("Kity", 200));
mp.insert(pair<string, double>("Memi", 500));
//重复插入键值"Jack";
mp.insert(pair<string, double>("Jack", 306));
//使用前向迭代器中序遍历multimap;
multimap <string, double>:: iterator it;
cout << "The elements before deleted : " << endl;
for(it=mp.begin(); it != mp.end(); it++) {
cout << (*it).first << " " << (*it).second << endl;
}
//删除键值等于“Jack”的元素;
mp.erase("Jack");
cout << "The elements after deleted : " << endl;
for(it=mp.begin(); it != mp.end(); it++) {
cout << (*it).first << " " << (*it).second << endl;
}
return 0;
}
multimap元素的查找
由于multimap存在重复的键值,所以find()方法只返回重复键值中的第一个元素的迭代器位置,如果没有找到该键值,则返回end()迭代器的位置,请看下例程序:
运行结果为:
All of the elements :
Jack 300.5
Jack 306
Kity 200
Memi 500
The searching result :
Jack 300.5
Not find it!
The Code Follows:
#include <iostream>
#include <map>
using namespace std;
int main()
{
//定义map对象,当前没有任何元素;
multimap <string, double> mp;
//插入元素;
mp.insert(pair<string, double>("Jack", 300.5));
mp.insert(pair<string, double>("Kity", 200));
mp.insert(pair<string, double>("Memi", 500));
//重复插入键值"Jack";
mp.insert(pair<string, double>("Jack", 306));
//使用前向迭代器中序遍历multimap;
multimap <string, double>:: iterator it;
cout << "All of the elements : " << endl;
for(it=mp.begin(); it != mp.end(); it++) {
cout << (*it).first << " " << (*it).second << endl;
}
//查找键值;
cout << endl << "The searching result :" << endl;
it = mp.find("Jack");
if(it != mp.end()) { //找到;
cout << (*it).first << " " << (*it).second << endl;
}else { //没找到;
cout << "Not find it!" << endl;
}
it = mp.find("Nacy");
if(it != mp.end()) { //找到;
cout << (*it).first << " " << (*it).second << endl;
}else { //没找到;
cout << "Not find it!" << endl;
}
return 0;
}