On Thursday, 26 November 2015 at 17:27:34 UTC, André wrote:
Hi,

I have a maybe trivial question on how to insert or update a given entry in a multidimensional AA. So I have this AA:

   /// language, chapter, section. Content is a magic struct
   Content[int][string][string] contentAA;

In some part of my code I want to either add a complete new entry or update an existing one. I just came up with this solution but it seems complex to me:

   string language, chapter;
   int section;
   Content* content;
   if (auto l = language in contentAA) {
       if (auto c = chapter in *l) {
              content = section in *c;
       }
   }
   if (!content) {
       contentAA[language][chapter][section] = Content();
       content = &contentAA[language][chapter][section];
   }
/// work with content regardless whether it is updated or newly inserted

My question now is: is there some more elegant solution to achieve this? Something like in C++ when you have std::map's of std::map's and just access the elements and the entry is created implicitly? Basically I would want to just have this line working out of the box:

   content = &contentAA[language][chapter][section];

.. and the AA would make sure the element is created if it didn't exist before. I know I could create a function for that but I am looking for a standard approach that already exists.

Thanks!
André

AA are weird in that AFAIK you need to "initialise" them before you try to look suff up in them else they crash. i.e.
int[string] foo;
// auto e = "1" in foo; // crash AA not initialised
foo[ "blah"] = 0;
foo.remove("blah");
auto e = "1" in foo; //doesn't crash

have you tried using aa.get(key,default);?
i.e. contentAA.get(language,"english").get(section, "somedefault").get(section,0);


other than that are you likey to have missing sections? (i.e. do you need an AA for section or can you just use an array?) similarly; does chapter need to be indexed by string? can you get away with indexing by chapter number and storing an array of chapter names and looking that up when needed?

Nic

Reply via email to