cpp 如何遍历std::unordered_map<int, std::vector<int>>
时间: 2025-02-15 11:18:47 浏览: 74
在 C++ 中,遍历 `std::unordered_map<int, std::vector<int>>` 类型的数据结构可以分为两个步骤:首先,迭代整个 map;其次,对于每个 key-value 对,再遍历对应的 vector。
下面是一个简单的示例,展示如何遍历这样的数据结构:
```cpp
#include <iostream>
#include <unordered_map>
int main() {
// 创建一个 unordered_map
std::unordered_map<int, std::vector<int>> myMap = {
{1, {2, 3, 4}},
{5, {6, 7, 8}},
{9, {10, 11, 12}}
};
for (const auto& pair : myMap) {
int key = pair.first;
std::vector<int> values = pair.second;
std::cout << "Key: " << key << ", Vector: ";
for (int value : values) {
std::cout << value << " ";
}
std::cout << "\n";
}
return 0;
}
```
在这个例子中,我们使用 `for_each` 或者范围-based for循环 (`for (const auto& pair : myMap)`) 来遍历 map 的每一项。然后,分别访问 key 和对应的 vector。对于 vector,我们再次使用 range-based for 循环来遍历其元素。
阅读全文
相关推荐



















