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

发布时间 2023-06-03 22:14:00作者: 我当道士那儿些年

请帮我写一段代码。 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;
}