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

C++中如何实现int键映射多整数值的字典以构建图结构

C++ 实现int键对应多整数值字典的方案

你原有代码报错的核心原因是:std::map 的值类型不能使用原生数组 int[],原生数组不满足STL容器要求的可拷贝、可赋值特性,无法直接作为map的值使用。

常用实现方案

方案1:std::map + std::vector(构建图邻接表最常用)

适合允许存储重复关联值、需要随机访问元素的场景,是构建图结构的首选写法:

#include <map>
#include <vector>

int main() {
    // 定义键为int,值为int类型动态数组的map
    std::map<int, std::vector<int>> miasta;
    // 批量赋值
    miasta[0] = {1, 2, 3};
    // 逐个追加元素
    miasta[1].push_back(4);
    miasta[1].push_back(5);

    // 初始化时直接批量构造,和你给出的Python写法逻辑一致
    std::map<int, std::vector<int>> cities = {
        {1, {1, 2, 3}},
        {2, {1, 2, 3}}
    };
    return 0;
}

方案2:std::map + std::unordered_set/std::set(和Python集合行为一致)

如果不需要存储重复的关联值,和你给出的Python示例中使用{}集合的逻辑一致,自动对值去重:

#include <map>
#include <unordered_set>

int main() {
    // 哈希实现的无序集合,插入查找效率更高
    std::map<int, std::unordered_set<int>> cities = {
        {1, {1, 2, 3}},
        {2, {1, 2, 3}}
    };
    // 插入新值,重复插入自动忽略
    cities[3].insert(4);
    return 0;
}

如果需要关联值自动排序,可以把std::unordered_set替换为std::set即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 01:57:04