std::list<std::map<std::string, std::string>> 遍历循环 并从std::map取指定值
时间: 2023-09-10 17:11:02 浏览: 98
可以使用嵌套的迭代器来遍历 `std::list<std::map<std::string, std::string>>` 并从 `std::map` 中获取指定的值,示例代码如下:
```c++
#include <iostream>
#include <list>
#include <map>
#include <string>
int main() {
std::list<std::map<std::string, std::string>> lst = {
{{"name", "Alice"}, {"age", "20"}},
{{"name", "Bob"}, {"age", "30"}},
{{"name", "Charlie"}, {"age", "40"}}
};
// 遍历 std::list<std::map<std::string, std::string>>
for (auto it1 = lst.begin(); it1 != lst.end(); ++it1) {
// 获取 std::map<std::string, std::string>
auto& mp = *it1;
// 从 std::map<std::string, std::string> 中获取指定值
auto name_it = mp.find("name");
auto age_it = mp.find("age");
if (name_it != mp.end() && age_it != mp.end()) {
std::cout << name_it->second << ", " << age_it->second << std::endl;
}
}
return 0;
}
```
输出结果为:
```
Alice, 20
Bob, 30
Charlie, 40
```
在循环中,`it1` 是一个指向 `std::map<std::string, std::string>` 的迭代器,可以通过 `*it1` 获取 `std::map<std::string, std::string>` 的引用。然后使用 `find` 函数来查找指定的键,如果找到了就可以通过迭代器的 `second` 成员来获取对应的值。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.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://img-home.csdnimg.cn/images/20241226111658.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://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)