multimap中可以保存多个key值,介绍一下获取某一key值所有value的方法。这些方法对于multiset也是可以使用的。
- 使用equal_range
- 使用count统计出数量
- 使用lower_bound upper_bound获取起止迭代器,和1类似
代码:
#include <iostream>
#include <map>
using namespace std;
typedef multimap<string, string>::iterator It;
int main() {
multimap<string, string> names;
names.insert(pair<string, string>("zhang", "san"));
names.insert(pair<string, string>("li", "si"));
names.insert(pair<string, string>("wang", "wu"));
names.insert(pair<string, string>("zhao", "liu"));
names.insert(pair<string, string>("zhang", "qi"));
names.insert(pair<string, string>("zhang", "ba"));
//use equal_range
pair<It, It> ret;
ret = names.equal_range("zhang");
for(It it = ret.first; it != ret.second; ++it) {
cout << " " << it->second;
}
cout << "\n";
//use count
It it = names.find("zhang");
for (int i = 0, len = names.count("zhang"); i < len; ++i, ++it) {
cout << " " << it->second;
}
cout << "\n";
//use upper_bound lower_bound
It start, end;
start = names.lower_bound("zhang");
end = names.upper_bound("zhang");
for (It it = start; it != end; ++it) {
cout << " " << it->second;
}
cout << "\n";
return 0;
}