c++ - 如何在 C++ 中实现与嵌套 Perl 散列等效的功能?

标签 c++ perl stl

我想将一些 Perl 代码更改为 C++。我需要知道如何在 C++ 中实现嵌套的 Perl 哈希。我认为 STL 是一个不错的选择,并使用了 map 。在 map 的帮助下,我只能创建一个简单的散列,但我不知道如何创建嵌套的散列结构。

我的 Perl 哈希是这样的:

%foo = (
    "bar1" => {
        Default => 0,
        Value   => 0
    },
    "bar2" => {
        Default => 2,
        value   => 5,
        other   => 4
    }
)

我可以这样修改它:$foo{"bar1"}->{"Default"} = 15

我如何使用 STL 在 C++ 中执行此操作?也许这是一个简单的问题,但我无法弄清楚。

最佳答案

您可能需要类型:

std::map< std::string, std::map<std::string, int> > 

您可能需要改用struct(或class)。

struct Element {
    int default;
    int value;
    int other;
    Element(): default(0), value(0), other(0)
    { }
    Element(int default_, int value_, int other_)
    : default(default_)
    , value(value_)
    , other(other_)
    { }
};

int main() {
    std::map<std::string, Element> elements;
    elements["bar1"]; // Creates element with default constructor
    elements["bar2"] = Element(2,5,4);
    elements["bar3"].default = 5; // Same as "bar1", then sets default to 5
    return 0;
}

关于c++ - 如何在 C++ 中实现与嵌套 Perl 散列等效的功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3601105/

相关文章:

c++ - C/C++宏扩展

c++ - Linux中的信号处理和中断函数调用?

perl - 按降序对第 5 列进行排序错误消息

linux - 在 Perl 中打印 shell 命令的输出

c++ - 讨论了哪些 boost 库包含在 C++17 中?

c++ - 如何创建与给定函数具有相同类型的变量?

C++ -- "throw new BadConversion("xxx")"and "throw BadConversion ("xxx")"之间的区别

perl - 为什么 Moose 代码这么慢?

c++ - 使用adjacent_difference编译错误

c++ - 在 C++ 中,在 STL 容器中存储具有重载 "operator&"的类对象是否合法?