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
相关产品推荐
相关产品推荐

