mutimap如何遍历
时间: 2023-06-29 14:03:23 浏览: 45
`multimap` 是一个关联容器,其中的元素是按照键值进行排序的,因此遍历 `multimap` 与遍历数组或其他容器有所不同。
可以使用迭代器来遍历 `multimap`。以下是两种常用的遍历方式:
1. 使用迭代器范围遍历
```cpp
#include <iostream>
#include <map>
int main() {
std::multimap<int, std::string> myMap;
myMap.insert(std::make_pair(1, "one"));
myMap.insert(std::make_pair(2, "two"));
myMap.insert(std::make_pair(2, "second two"));
myMap.insert(std::make_pair(3, "three"));
for (auto it = myMap.begin(); it != myMap.end(); ++it) {
std::cout << it->first << ": " << it->second << std::endl;
}
return 0;
}
```
输出结果:
```
1: one
2: two
2: second two
3: three
```
2. 使用 `equal_range` 遍历指定键值范围
```cpp
#include <iostream>
#include <map>
int main() {
std::multimap<int, std::string> myMap;
myMap.insert(std::make_pair(1, "one"));
myMap.insert(std::make_pair(2, "two"));
myMap.insert(std::make_pair(2, "second two"));
myMap.insert(std::make_pair(3, "three"));
auto range = myMap.equal_range(2);
for (auto it = range.first; it != range.second; ++it) {
std::cout << it->first << ": " << it->second << std::endl;
}
return 0;
}
```
输出结果:
```
2: two
2: second two
```