Home > Software design >  Macro for nested maps in C
Macro for nested maps in C

Time:10-05

Is it possible to create simple interface to create nested std::maps in C ? If this is possbile, can I go advanced and make it with different nested maps/vectors

CreateMaps(4); returns std::map<int,std::map<int,std::map<int,std::map<int,int>>>>>

CreateMaps(3); returns std::map<int,std::map<int,std::map<int,int>>>>

I am not really sure if this counts as macro or no.

My final target is to create maps at init and I want to divide into categories, type_0 has X subtypes which has Y subtypes and so on..., and I want to count how many times I reach certain scenario. Creating the map is defined after parsing a file, so I dont know the size and the number of nested maps at compile time.

CodePudding user response:

Yes you can, even without macros, but by using recursive templates. Here is what it could look like:

// Recursive definition
template<typename T, size_t N>
struct NestedMap {
    using type = std::map<T, typename NestedMap<T, N - 1>::type>;
};

// Termination condition for the recursion
template<typename T>
struct NestedMap<T, 0> {
    using type = T;
};

// Just a convenience
template<typename T, size_t N>
using NestedMap_t = NestedMap<T, N>::type;

And then you can use it like so:

NestedMap_t<int, 4> quadmap;
quadmap[1][2][3][4] = 42;

However, nesting containers is often not very efficient, and you might get better performance by flattening your data structure. If you want to have a map that is indexed by four integers, then you could also do:

std::map<std::array<int, 4>, int> quadmap;
quadmap[{1, 2, 3, 4}] = 42;

The above types are fixed at compile time. If you want something more flexible, you should make the map's key and value more dynamic. Consider:

std::map<std::vector<int>, std::any> anymap;
anymap[{1, 2, 3, 4}] = 42;
  •  Tags:  
  • c
  • Related