unordered_map<string, struct>如果是结构体如何遍历
时间: 2023-12-24 11:09:01 浏览: 98
DFA.zip_DFA
可以使用 C++11 新增的范围遍历语法,对 `unordered_map` 中的键值对进行遍历,代码示例如下:
```c++
#include <iostream>
#include <unordered_map>
#include <string>
struct Person {
int age;
std::string address;
};
int main() {
std::unordered_map<std::string, Person> personMap = {
{"Tom", {20, "Beijing"}},
{"Jerry", {25, "Shanghai"}},
{"Kate", {18, "Guangzhou"}}
};
// 使用范围遍历语法访问 unordered_map 中的键值对
for (const auto& [name, person] : personMap) {
std::cout << "Name: " << name << ", Age: " << person.age
<< ", Address: " << person.address << std::endl;
}
return 0;
}
```
输出结果为:
```
Name: Tom, Age: 20, Address: Beijing
Name: Jerry, Age: 25, Address: Shanghai
Name: Kate, Age: 18, Address: Guangzhou
```
阅读全文