c++进行map数据横向合并

请帮我写一段代码。 nlohmann::json怎么把三个字典合并到一起,c++ 14标准,并且每个字典的长度不一样,原数据不是json。 例如:

data1 = [{"key1": "a1", "key2": 1}, {"key1": "a2", "key2": 2}]

data2 = [{"key3": "b1",}, {"key3": "b1",}]

data3 = [{"key4": "cc", "key5": 5, "key6": 1.01},{"key4": "cc", "key5": 5, "key6": 1.01}]

最终想要的数据:

data = [

{"key1": "a1", "key2": 1, "key3": "b1", "key4": "cc", "key5": 5, "key6": 1.01},

{"key1": "a1", "key2": 1, "key3": "b1", "key4": "cc", "key5": 5, "key6": 1.01},

]

复制代码
#include <iostream>
#include <vector>
#include <nlohmann/json.hpp>

using json = nlohmann::json;

int main() {
    // 创建原始数据
    std::vector<std::map<std::string, json>> data1 = {
        {{"key1", "a1"}, {"key2", 1}},
        {{"key1", "a2"}, {"key2", 2}}
    };
    std::vector<std::map<std::string, json>> data2 = {
        {{"key3", "b1"}},
        {{"key3", "b1"}}
    };
    std::vector<std::map<std::string, json>> data3 = {
        {{"key4", "cc"}, {"key5", 5}, {"key6", 1.01}},
        {{"key4", "cc"}, {"key5", 5}, {"key6", 1.01}}
    };

    // 创建结果容器
    std::vector<std::map<std::string, json>> mergedData;

    // 合并数据
    for (size_t i = 0; i < data1.size(); ++i) {
        std::map<std::string, json> mergedItem;
        mergedItem.insert(data1[i].begin(), data1[i].end());
        mergedItem.insert(data2[i].begin(), data2[i].end());
        mergedItem.insert(data3[i].begin(), data3[i].end());
        mergedData.push_back(mergedItem);
    }

    // 转换为 nlohmann::json 对象
    json jsonData = mergedData;

    // 打印最终结果
    std::cout << jsonData.dump() << std::endl;

    return 0;
}
复制代码

 

posted @   我当道士那儿些年  阅读(124)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 字符编码:从基础到乱码解决
点击右上角即可分享
微信分享提示