Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement a multi-dimensional associative array in C++?

I am porting some SystemVerilog to SystemC/C++ and am having trouble with a multidimensional associative array. Consider the declaration of this array in SV.

// assume typ_one, typ_two, typ_three are struct or enum types
typ_one mda[typ_two][typ_two][typ_three];

I know with 1-D associative arrays I can use a map, and with 2-D arrays a nested map, and I believe a similar approach can solve the multidimensional array but it gets really messy.

typ_one mda[typ_two];
map< typ_two, typ_one >;

typ_one mda[typ_two][typ_two];
map< typ_two, map< typ_two, typ_one > >;

typ_one mda[typ_two][typ_two][typ_three];
map< typ_two, map< typ_two, map< typ_three, typ_one > > >;

So my questions are,

(1) is the above correct, in the sense that an operation in the form of mda[x][y][z] will return the same expected value as with the SV code?

(2) is there a better, cleaner way?

like image 232
Rich Avatar asked Jul 18 '26 18:07

Rich


1 Answers

Your std::map examples will do what you want.

Unfortunately there is no cleaner way, because C++ doesn't have special syntax for associative arrays like it does for normal arrays (and unfortunately those are primitive "raw" arrays, not array objects like in Java/C#).

like image 123
user1610015 Avatar answered Jul 20 '26 07:07

user1610015



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!