简体   繁体   中英

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?

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#).

  template<class T1, class T2, class ... Ts>
  struct MultiDimensionalMap{
      typedef std::map<T1, typename MultiDimensionalMap<T2,Ts...>::map_type> map_type;
  };

  template<class T1, class T2>
  struct MultiDimensionalMap<T1,T2>{
      typedef std::map<T1,T2> map_type;

  };

With this, for your example you would use the following

MultiDimensionalMap<type_two,type_two,type_three,type_one>::map_type m;

There are at least two approaches to implementing that.

  • The first would be using nested maps, as you suggest yourself in your question: map of maps or maps etc. to the desired level of nesting.

  • The second would be to use an ordinary linear map in which the key is a tuple of indices (ie 3 indices for a 3D associative array).

I would actually consider following the second approach, unless you have a specific reason to stick to the first.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM