You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Python中{int: [int, list]}类型的字典迁移实现到C++

C++实现对应Python字典结构的方案

你之前仅定义了单个pair对象,无法实现按键查找的需求。C++中对应Python字典的关联容器为std::map(有序,键自动排序)或std::unordered_map(无序,查找性能更高),搭配嵌套pair存储step字段和队列即可满足所有需求。


完整实现代码

#include <iostream>
#include <map>
#include <deque>

int main() {
    // 定义数据结构:键为int,值为pair<step(int), 存储整数的deque>
    std::map<int, std::pair<int, std::deque<int>>> dct;

    // 循环生成初始结构:1-4的step均为0,队列为空
    for (int i = 1; i <= 4; ++i) {
        dct[i] = {0, {}};
    }

    // 修改对应键的step和队列内容
    dct[1].first = 1;
    dct[1].second.push_back(5);
    dct[1].second.push_back(1);

    dct[2].first = 2;
    dct[2].second.push_back(1);
    dct[2].second.push_back(1);

    dct[3].second.push_back(1);
    dct[3].second.push_back(2);
    dct[3].second.push_back(3);
    dct[3].second.push_back(4);

    dct[4].second.push_back(1);
    dct[4].second.push_back(17);

    // 遍历输出结果
    std::cout << "{" << std::endl;
    for (const auto& entry : dct) {
        int key = entry.first;
        int step = entry.second.first;
        const auto& q = entry.second.second;
        std::cout << "  " << key << ": [" << step << ", [";
        for (size_t i = 0; i < q.size(); ++i) {
            if (i != 0) std::cout << ", ";
            std::cout << q[i];
        }
        std::cout << "]]," << std::endl;
    }
    std::cout << "}" << std::endl;

    // 可选:安全查找逻辑,避免不存在的键被自动插入
    int target_key = 3;
    if (dct.count(target_key)) {
        std::cout << "键" << target_key << "的step值为:" << dct[target_key].first << std::endl;
    }

    return 0;
}

输出结果

{
  1: [1, [5, 1]],
  2: [2, [1, 1]],
  3: [0, [1, 2, 3, 4]],
  4: [0, [1, 17]],
}

如果不需要键有序,将std::map替换为std::unordered_map即可,其余操作完全一致,查找效率更高。


内容的提问来源于stack exchange,提问作者Homayoon Soleimani

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 14:24:06