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

如何在C++中创建带有预定义键的map?

在C++中实现带预定义键的类式Map

你可以通过以下几种方式实现类似Python中继承dict的带预定义键的结构,满足通过字符串键访问预定义变量的需求:

方式1:继承标准容器直接初始化

直接继承std::unordered_map(或std::map),在构造函数中初始化预定义键值对,用法和你示例中的Python实现最接近:

#include <unordered_map>
#include <string>

class SomeClass : public std::unordered_map<std::string, int> {
public:
    SomeClass() {
        (*this)["a"] = 1;
        (*this)["b"] = 2;
        (*this)["c"] = 3;
    }
};

使用示例

完全符合你给出的函数调用场景:

int someFunction(SomeClass& c, const std::string& variableName) {
    if (c[variableName] < 10) {
        // 你的业务逻辑
    }
    // 其他处理代码
    return 0;
}

注意:这种方式允许外部代码添加新的键值对,如果需要严格限制只能使用预定义键,可以参考下面的封装方式。

方式2:封装容器并限制键的访问

如果要确保只能访问预定义的键,避免意外添加新键,可以将map作为类的私有成员,通过重载operator[]来提供访问,并在键不存在时抛出异常:

#include <unordered_map>
#include <string>
#include <stdexcept>

class SomeClass {
private:
    std::unordered_map<std::string, int> data_;
public:
    SomeClass() {
        data_["a"] = 1;
        data_["b"] = 2;
        data_["c"] = 3;
    }

    // 只读访问版本
    int operator[](const std::string& key) const {
        auto iter = data_.find(key);
        if (iter == data_.end()) {
            throw std::invalid_argument("访问了未预定义的键");
        }
        return iter->second;
    }

    // 可写访问版本
    int& operator[](const std::string& key) {
        auto iter = data_.find(key);
        if (iter == data_.end()) {
            throw std::invalid_argument("访问了未预定义的键");
        }
        return iter->second;
    }
};

这种方式能严格控制可用的键,避免误操作添加不属于预定义集合的键值对。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 03:42:17