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

如何在C++中实现类似Python的字符串键字典,用词汇标注列表?

C++实现字符串键映射列表结构方案

完全可以实现,C++标准库已经提供了原生支持该需求的容器,不需要额外引入第三方依赖。

容器选择

你需要的是键为字符串类型、值为字符串数组的关联容器,C++标准库提供两种常用选择:

  • 如果你需要键自动按字典序排序,选择std::map,底层为红黑树实现,查找时间复杂度O(log n)
  • 如果你不需要排序、追求更高的插入/查找性能,选择std::unordered_map,底层为哈希表实现,平均查找时间复杂度O(1)

完整实现示例

#include <iostream>
#include <unordered_map> // 若使用std::map则替换为<map>头文件
#include <vector>
#include <string>

int main() {
    // 定义匹配需求的容器结构:键为string类型,值为string类型的动态数组
    std::unordered_map<std::string, std::vector<std::string>> food_ingredients;

    // 写入示例数据,用法和Python字典高度相似
    food_ingredients["Cookie"] = {"sugar", "chocolate", "flour"};
    food_ingredients["Pie"] = {"milk", "apples", "flour"};

    // 直接用字符串作为键访问对应的原料列表
    std::cout << "Cookie的原料:" << std::endl;
    for (const auto& item : food_ingredients["Cookie"]) {
        std::cout << "- " << item << std::endl;
    }

    // 遍历所有键值对
    std::cout << "\n所有食品原料清单:" << std::endl;
    for (const auto& entry : food_ingredients) {
        std::cout << entry.first << ":";
        for (size_t i = 0; i < entry.second.size(); i++) {
            if (i > 0) std::cout << "、";
            std::cout << entry.second[i];
        }
        std::cout << std::endl;
    }

    return 0;
}

注意事项

  • 上述语法支持C11及以上版本,如果使用更早的C标准,需要用push_back方法逐个插入vector元素,不能直接用花括号批量初始化
  • 如果要判断某个键是否存在,可以调用容器的count()方法:if (food_ingredients.count("Cookie")) { ... },避免访问不存在的键时容器自动插入空值

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 22:57:01