multimap
表示有序的键值对,它在
map
的基础上多了:允许重复的key,甚至是重复的(key:value)。
头文件为#include map
。
1 insert()
插入操作为:
a.insert({key,val}) //插入一个键值对
a.insert({{key1, val1},{key2, val2}}) //插入多个键值对
实例代码为,
#include <iostream>
#include <map>
using namespace std;
int main() {
multimap<int, int> m;
//m[1] = 1;这样的赋值方式对于multimap是不被允许的,会报错
m.insert({5,5});
m.insert({1,1});
m.insert({1,1});
m.insert({1,2});
m.insert({2,2});
m.insert({3,3});
m.insert({4,4});
m.insert({{6,6},{7,7}});
for (auto [key, val] : m) {
cout << "key = " << key << ", val = " << val << endl;
}
return 0;
}
代码输出为:
key = 1, val = 1
key = 1, val = 1
key = 1, val = 2
key = 2, val = 2
key = 3, val = 3
key = 4, val = 4
key = 5, val = 5
key = 6, val = 6
key = 7, val = 7
2 equal_range()
auto range = a.equal_range(key); //返回哈希表中键等于key的迭代器pair
//即std::pair<const_iterator,const_iterator>
代码如下,
#include <iostream>
#include <map>
using namespace std;
int main() {
multimap<char, int> m;
m.insert({{'a', 1}, {'b', 2}, {'b', 3}, {'b', 4}, {'c', 5}});
auto range = m.equal_range('b');
for (auto it = range.first; it != range.second; it++) {
cout << "key = " << it->first << ", value = " << it->second << endl;
}
return 0;
}
程序输出为,
key = b, value = 2
key = b, value = 3
key = b, value = 4
更多信息:待更新。。。