声明unordered_map,并且循环遍历std::unordered_map<int, FuncServerPtr> m_cmd,举例
时间: 2024-04-26 19:19:13 浏览: 12
unordered_map是C++ STL中的一种关联容器,它存储的数据是以键值对的形式出现,且具有快速查找的特点。其中,键(key)和值(value)都可以是任何可复制的数据类型。
下面是声明一个unordered_map的示例:
```
#include <unordered_map>
using namespace std;
unordered_map<int, string> myMap; //声明一个存储int和string类型的unordered_map
```
循环遍历unordered_map可以使用迭代器来实现,具体代码如下:
```
#include <unordered_map>
using namespace std;
int main() {
unordered_map<int, string> myMap = {{1, "CSDN"}, {2, "AI"}};
// 遍历unordered_map
for (auto it = myMap.begin(); it != myMap.end(); ++it) {
cout << "Key: " << it->first << ", Value: " << it->second << endl;
}
return 0;
}
```
上述代码中,我们使用auto关键字定义了一个迭代器it,it指向myMap的起始位置,然后通过it++来遍历整个myMap。
相关问题
声明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中,并使用迭代器遍历这个容器,在遍历过程中,我们打印出每个键的值并调用相应的函数。
遍历std::unordered_map
遍历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可以获取键和值。