#include <map>  
#include <string>
#include <iostream>
using namespace std;

int main()
{
///1. 初始化
multimap<int, string, greater<int>> mapStudent;
multimap<int, string>::iterator iter, beg, end;

///2. 添加元素
///multimap不支持下标操作
mapStudent.insert(pair<int, string>(0, "student_one_1"));
mapStudent.insert(pair<int, string>(0, "student_one_2"));///一对多
mapStudent.insert(pair<int, string>(0, "student_one_3"));///一对多
mapStudent.insert(pair<int, string>(1, "student_two"));
mapStudent.insert(pair<int, string>(5, "Fear Kubrick"));
mapStudent.insert(pair<int, string>(2, "Akemi Homura"));
mapStudent.insert(pair<int, string>(-1, "Eren Jaeger"));
mapStudent.insert(pair<int, string>(99, "lin"));
cout << "总数:" << mapStudent.size() << endl;
cout << endl;

///3. 遍历
for (iter = mapStudent.begin(); iter != mapStudent.end(); iter++)
cout << iter->first << " " << iter->second << endl;
cout << endl;

///4. 单键查询与范围查询
///单键查询
int count = mapStudent.count(0);
iter = mapStudent.find(0);
for (int i = 0; i < count; i++, iter++)
cout << iter->first << " " << iter->second << endl;
cout << endl;


///5. 删除
iter = mapStudent.find(1);
mapStudent.erase(iter);
cout << "总数:" << mapStudent.size() << endl;
for (iter = mapStudent.begin(); iter != mapStudent.end(); iter++)
cout << iter->first << " " << iter->second << endl;
cout << endl;

///6. 删除多个相同key中的特定一个
int count2 = mapStudent.count(0);
iter = mapStudent.find(0);
for (int i = 0; i < count2; i++, iter++){
if(iter->first == 0 && iter->second == "student_one_2"){
mapStudent.erase(iter);
}
}

cout << "总数:" << mapStudent.size() << endl;
for (iter = mapStudent.begin(); iter != mapStudent.end(); iter++)
cout << iter->first << " " << iter->second << endl;
cout << endl;



///7. 判空与清空
if (!mapStudent.empty()){
mapStudent.clear();
}

}

C++ multimap 用法总结 例子_i++

C++ multimap 用法总结 例子_i++_02 


倒序添加std::greater<int>

C++ multimap 用法总结 例子_#include_03

​C++ STL 练手(multimap的使用) - 简书​

关注公众号:微程序学堂