Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Struct containing a Map in a Map? (C++/STL)

Tags:

c++

stl

I was wondering if it was possible to create a struct containing a number of variables and a map in a map.

What I have at the moment:

typedef std::map<std::string,double> lawVariables;  

struct ObjectCustomData {   
  std::string objectType;    
  bool global_lock;   
  std::map<std::string, lawVariables> lawData;   
 };

This struct is then passed on to another function as a single data block for that object.

The structure setup is as follows: Each object has a data block that contains: its ObjectType, a bool for a lock, and a varying number of "laws" that could look like this:

law1 -> var_a = 39.3;
     -> var_g = 8.1;
law8 -> var_r = 83.1;
     -> var_y = 913.3;
     -> var_a = 9.81;

Firstly, I'm unsure whether I should be using a Map within a Map and secondly even if this would be valid, I'm unsure how to fill it with data and how to recall it afterwards. I looked at maps because then I can search (on a name) if a certain object has a certain law, and if that law has certain variables.

(sorry for the first messy post appearance, hope this is better :) )

like image 344
Karrok Avatar asked Nov 20 '25 18:11

Karrok


1 Answers

I was wondering if it was possible to create a struct containing a number of variables and a map in a map

Yes. It is possible to have Map as value inside another map.

If you are particular about the order of insertion and the entries are less for inner map then your data structure can looks like:

typedef std::vector<std::pair<std::string,double> > lawVariables;  

struct ObjectCustomData {   
  std::string objectType;    
  bool global_lock;   
  std::map<std::string, lawVariables> lawData;   
 };

EDIT: I saw your edit now. If lookup is your primary requirement then go for map.

Example:

 typedef std::map<std::string,double> lawVariables;  

    struct ObjectCustomData {   
      std::string objectType;    
      bool global_lock;   
      std::map<std::string, lawVariables> lawData;   
     };

void test(ObjectCustomData& data)
{
  lawVariables& variable = data.lawData["law_1"];
  variable["var_a"] = 39.3;

}
like image 79
aJ. Avatar answered Nov 23 '25 06:11

aJ.



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!