std::map<std::string, std::string> 遍历
时间: 2023-09-10 12:11:18 浏览: 58
可以使用迭代器来遍历 std::map<std::string, std::string>,示例代码如下:
```cpp
#include <iostream>
#include <map>
#include <string>
int main() {
std::map<std::string, std::string> myMap;
myMap["apple"] = "red";
myMap["banana"] = "yellow";
myMap["grape"] = "purple";
// 使用迭代器遍历 map
std::map<std::string, std::string>::iterator it;
for (it = myMap.begin(); it != myMap.end(); it++) {
std::cout << it->first << " is " << it->second << std::endl;
}
return 0;
}
```
输出结果:
```
apple is red
banana is yellow
grape is purple
```
相关问题
std::list<std::map<std::string, std::string>> 遍历
可以使用嵌套循环来遍历 `std::list<std::map<std::string, std::string>>`。具体实现如下:
```c++
#include <iostream>
#include <list>
#include <map>
#include <string>
int main() {
std::list<std::map<std::string, std::string>> my_list = {
{{"name", "Alice"}, {"age", "20"}},
{{"name", "Bob"}, {"age", "30"}},
{{"name", "Charlie"}, {"age", "40"}}
};
for (const auto& my_map : my_list) {
for (const auto& [key, value] : my_map) {
std::cout << key << ": " << value << std::endl;
}
std::cout << std::endl;
}
return 0;
}
```
这里使用了 C++17 的结构化绑定 (structured binding),可以更方便地获取 map 中的键值对。输出结果为:
```
name: Alice
age: 20
name: Bob
age: 30
name: Charlie
age: 40
```
std::list<std::map<std::string, std::string>> 遍历循环
你可以使用两个嵌套的循环来遍历 `std::list<std::map<std::string, std::string>>`。外层循环遍历 `std::list` 中的每个元素,内层循环遍历每个 `std::map` 中的键值对。
以下是示例代码:
```cpp
#include <iostream>
#include <list>
#include <map>
#include <string>
int main() {
// 创建一个 std::list<std::map<std::string, std::string>> 对象
std::list<std::map<std::string, std::string>> data = {
{{"name", "Alice"}, {"age", "25"}},
{{"name", "Bob"}, {"age", "30"}},
{{"name", "Charlie"}, {"age", "35"}}
};
// 遍历 std::list<std::map<std::string, std::string>>
for (const auto& item : data) {
// 遍历 std::map<std::string, std::string>
for (const auto& pair : item) {
std::cout << pair.first << ": " << pair.second << std::endl;
}
std::cout << std::endl; // 每个 std::map 之间输出一个空行
}
return 0;
}
```
输出结果为:
```
name: Alice
age: 25
name: Bob
age: 30
name: Charlie
age: 35
```