遍历std::unordered_map
时间: 2024-03-18 22:37:42 浏览: 20
遍历std::unordered_map可以使用迭代器来实现。以下是一种常见的遍历方式:
```cpp
#include <iostream>
#include <unordered_map>
int main() {
std::unordered_map<int, std::string> myMap = {{1, "apple"}, {2, "banana"}, {3, "orange"}};
// 使用迭代器遍历unordered_map
for (auto it = myMap.begin(); it != myMap.end(); ++it) {
std::cout << "Key: " << it->first << ", Value: " << it->second << std::endl;
}
return 0;
}
```
在上述代码中,我们首先创建了一个std::unordered_map对象myMap,并初始化了一些键值对。然后,我们使用for循环和迭代器来遍历myMap。迭代器it指向当前键值对,通过it->first和it->second可以获取键和值。
相关问题
C++逆向遍历std::unordered_map的方法
在 C++ 中,可以使用反向迭代器 `rbegin()` 和 `rend()` 遍历容器的元素。对于 `std::unordered_map`,可以使用 `unordered_map::reverse_iterator` 类型来定义反向迭代器。
以下是一个简单的示例代码,展示如何使用反向迭代器遍历 `std::unordered_map` 的元素:
```c++
#include <iostream>
#include <unordered_map>
int main() {
std::unordered_map<std::string, int> myMap = {{"a", 1}, {"b", 2}, {"c", 3}};
// 反向遍历 unordered_map
for (auto it = myMap.rbegin(); it != myMap.rend(); ++it) {
std::cout << it->first << " : " << it->second << std::endl;
}
return 0;
}
```
输出结果为:
```
c : 3
b : 2
a : 1
```
需要注意的是,反向遍历是以键值对的形式进行的,其中 `it->first` 表示键,`it->second` 表示值。
声明unordered_map,并且循环遍历std::unordered_map<int, 函数指针> m_cmd,举例
std::unordered_map是C++ STL中的一个容器,它提供了一种将键映射到值的方法。在这个容器中,每个键必须是唯一的,它们用于在O(1)时间内查找与特定键相关联的值。
下面是一个循环遍历std::unordered_map<int, 函数指针> m_cmd的示例:
```
#include <unordered_map>
#include <iostream>
void func1() {
std::cout << "Function 1 is called." << std::endl;
}
void func2() {
std::cout << "Function 2 is called." << std::endl;
}
void func3() {
std::cout << "Function 3 is called." << std::endl;
}
int main() {
std::unordered_map<int, void (*)()> m_cmd;
m_cmd = func1;
m_cmd = func2;
m_cmd = func3;
for (auto it = m_cmd.begin(); it != m_cmd.end(); ++it) {
std::cout << "Function pointer of key " << it->first << " is called." << std::endl;
it->second();
}
return 0;
}
```
在这个例子中,我们创建了一个std::unordered_map对象m_cmd,它的键是int类型,值是函数指针类型。我们添加了三个函数指针到m_cmd中,并使用迭代器遍历这个容器,在遍历过程中,我们打印出每个键的值并调用相应的函数。