Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I implement the equivalent of nested Perl hashes in C++?

Tags:

c++

stl

perl

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.

like image 860
saran Avatar asked Aug 30 '10 14:08

saran


People also ask

How do I access nested hash in Perl?

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.

How to create hash of hash in Perl?

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.

How do I loop through a hash in Perl?

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.

How do I print a hash in Perl?

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.


1 Answers

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;
}
like image 127
Notinlist Avatar answered Oct 13 '22 23:10

Notinlist