请教一下std::list转nlohmann::json的例子
时间: 2024-01-22 17:01:59 浏览: 139
可以按照以下步骤将std::list转换为nlohmann::json:
1. 包含必要的头文件:
```c++
#include <list>
#include <nlohmann/json.hpp>
```
2. 创建一个std::list:
```c++
std::list<int> mylist = {1, 2, 3, 4, 5};
```
3. 定义一个nlohmann::json对象:
```c++
nlohmann::json j;
```
4. 使用std::for_each函数将std::list中的元素添加到nlohmann::json对象中:
```c++
std::for_each(mylist.begin(), mylist.end(), [&j](int& val) {
j.push_back(val);
});
```
5. 现在,nlohmann::json对象j包含std::list中的所有元素。您可以使用nlohmann::json::dump()函数将其转换为JSON字符串:
```c++
std::string json_str = j.dump();
```
完整的示例代码如下所示:
```c++
#include <iostream>
#include <list>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
int main() {
std::list<int> mylist = {1, 2, 3, 4, 5};
json j;
std::for_each(mylist.begin(), mylist.end(), [&j](int& val) {
j.push_back(val);
});
std::string json_str = j.dump();
std::cout << json_str << std::endl;
return 0;
}
```
输出结果为:
```
[1,2,3,4,5]
```
阅读全文
相关推荐














