声明unordered_map,并且循环遍历std::unordered_map<int, 函数指针> m_cmd,举例
时间: 2024-04-26 18:19:14 浏览: 19
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中,并使用迭代器遍历这个容器,在遍历过程中,我们打印出每个键的值并调用相应的函数。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)