multimap
是一种关联容器,底层实现通常使用红黑树(Red-Black Tree),提供对元素的有序访问。其特点如下:
- 键值对是有序的,按键自动排序。
- 每个键可以对应多个值。
常见操作:
insert
:向multimap
插入元素,允许插入相同的键。find
:查找指定键的元素。erase
:删除指定键或键值对。begin
和end
:遍历容器中的元素。
示例代码:
#include <iostream>
#include <map>
int main() {
// 创建一个 multimap,键是 string,值是 string
std::multimap<std::string, std::string> multimap;
// 插入元素
multimap.insert({"fruit", "apple"});
multimap.insert({"fruit", "banana"});
multimap.insert({"fruit", "pear"});
multimap.insert({"vegetable", "carrot"});
multimap.insert({"vegetable", "spinach"});
// 输出所有键值对
std::cout << "All items in the multimap:" << std::endl;
for (const auto& pair : multimap) {
std::cout << pair.first << " -> " << pair.second << std::endl;
}
// 查找与"fruit"相关的所有元素
std::cout << "\nItems for fruit:" << std::endl;
auto range = multimap.equal_range("fruit");
for (auto it = range.first; it != range.second; ++it) {
std::cout << it->second << std::endl;
}
// 删除一个键值对
multimap.erase("fruit");
// 输出删除后的 multimap
std::cout << "\nAfter removing fruit:" << std::endl;
for (const auto& pair : multimap) {
std::cout << pair.first << " -> " << pair.second << std::endl;
}
return 0;
}
输出
All items in the multimap:
fruit -> apple
fruit -> banana
fruit -> pear
vegetable -> carrot
vegetable -> spinachItems for fruit:
apple
banana
pearAfter removing fruit:
vegetable -> carrot
vegetable -> spinach