我想将一些 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/