打印std::list<std::string>类型
时间: 2023-12-15 11:03:26 浏览: 44
以下是打印std::list<std::string>类型的示例代码:
```cpp
#include <iostream>
#include <list>
#include <string>
int main() {
std::list<std::string> strList = {"hello", "world", "!"};
for (const auto& str : strList) {
std::cout << str << " ";
}
std::cout << std::endl;
return 0;
}
```
输出结果为:
```
hello world !
```
相关问题
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
```