I want to change some Perl code into C++. I need to know how to implement nested Perl hashes in C++. I thought of STL as a good choice and used maps. With the help of maps I can create only a simple hash but I do not know how to create a nested hash structure.
My Perl hash is like this:
%foo = (
"bar1" => {
Default => 0,
Value => 0
},
"bar2" => {
Default => 2,
value => 5,
other => 4
}
)
I can modify it thus: $foo{"bar1"}->{"Default"} = 15
.
How do I do this in C++ using STL? Maybe this is a simple question but I am not able to figure it out.
Nested hashes are addressed by chaining the keys like so: $hash{top_key}{next_key}{another_key}; # for %hash # OR $hash_ref->{top_key}{next_key}{another_key}; # for refs. However since both of these "hashes" are blessed objects.
Among all of the Perl's nested structures, a Multidimensional hash or Hash of Hashes is the most flexible. It's like building up a record that itself contains a group of other records. The format for creating a hash of hashes is similar to that for array of arrays.
Loop over Perl hash values Perl allows to Loop over its Hash values. It means the hash is iterative type and one can iterate over its keys and values using 'for' loop and 'while' loop. In Perl, hash data structure is provided by the keys() function similar to the one present in Python programming language.
print "$ perl_print_hash_variable{'-hash_key2'} \n"; Description: The Perl print hash can used $ symbol for a single hash key and its value. The Perl print hash can use the % symbol for multiple hash keys and their values.
You may need the type:
std::map< std::string, std::map<std::string, int> >
You may need to use struct
(or class
) instead.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With