multimap
#include <iostream>
#include <map>
using namespace std;
void main() {
typedef nultimap<int, double, less<int> > mmid;
mmid pairs;
cout << pairs.count(15) << endl; // 没有输出
pairs.insert(mmid::value_type(15, 2.7));
pairs.insert(mmid::value_type(15, 99.3));
// 输出 2
cout << pairs.count(15) << endl; // 求关键字等于某值的元素个数
pairs.insert(mmid::value_type(30, 111.11));
pairs.insert(mmid::value_type(10, 22.22));
pairs.insert(mmid::value_type(25, 22.22));
pairs.insert(mmid::value_type(20, 22.22));
for(mmid::const_iterator i = pairs.begin(); i != pairs.end(); ++i)
// (10, 22.22),(15,2.7),(15,99.3),(20,22.22),(25,22.22),(30,111.11)
cout << "(" << i->first << "," << i->second << ")" << ",";
}
例题
#include <iostream>
#include <cmap>
#include <string>
using namespace std;
class Stu {
public:
typedef struct { // 类的内部还可以定义类
int id;
string name;
}Info;
int score;
Info info;
};
typedef multimap<int, Stu::Info> MAP_STD;
void main() {
MAP_STD mp;
Stu st;
string cmd;
while(cin >> cmd) {
if(cmd == "Add") {
cin >> st.info.name >> st.info.id >> st.score;
mp.insert(MAP_STD::value_type(st.score, st.info));
} else if (cmd == 'Query') {
int score;
cin >> score;
MAP_STD::iterator p = mp.lower_bound(score);
if(p != mp.begin()) {
--p;
score = p->first; // 比要查找的分数低的最高分
MAP_STD::iterator maxp = p;
int max_id = p->second->id;
for(; p != mp.begin() && p->first == score; --p) {
if(p->second.id > max_id) {
maxp = p;
max_id = p->second.id;
}
}
if(p->first == score) { // 如果上面循环因为 p==mp.begin()而终止,还要再操作
if(p->second.id > max_id) {
maxp = p;
max_id = p->second.id;
}
}
cout << maxp->second.name << " " maxp->second.id << " " << maxp->first << endl;
} else { //lower_bound的结果就是 begin,说明没人分数比查询分数低
cout << "Nobody" << endl;
}
}
}
}
- 注意
lower_bound
的使用,p != mp.begin()
是关键 - 插入还能这么写
mp.insert(make_pair(st.score, st.info));
map
map的[]成员函数
```cppinclude
include
using nanespace std;
void main() {
typedef map
int n = pairs[40]; // 如果没有关键字为40的元素,则插入一个
for(i = pairs.begin(); i != pairs.end(); ++i)
cout << *i << ",";
cout << endl; // (15,2.7),(20,9.3),(40,0),
pairs[15] = 6.28; // 把关键字为15的元素值改成6.28
for(i = pairs.begin(); i != pairs.end(); ++i)
cout << *i << ",";
cout << endl; // (15,6.28),(20,9.3),(40,0),
} ```