unkulunkulu
unkulunkulu

Reputation: 11912

Named sub-arrays of an array

I want to design a data structure with the following properties:

  1. Accessible as a single array of some type say T. For example s[i].
  2. Ability to access named ranges in it. For example s.GoodObjects[i], s.BadObjects[j].
  3. Iterate over it as a whole (STL algorithms etc.).
  4. Converting the name-index to index in the whole array. Here the interface is a good question too.

Also the desired behaviour would be the ability to

  1. I really want ranges names to be checked at compile time, not some string-named ranges, but C++ identifier-named.
  2. Add or remove elements to subarrays. s.BadObjects.push_back(yourMom).
  3. Implement it without using macros, just good C++ and templates, but readability of usages is of course the #1 priority.
  4. Possibly range arrays could have element type of a pointer to derived class where T is a pointer to base class.

So, how would you design such a structure?

Edit

Looks like I haven't stated it too explicitly, but the 4th requirement (the first list) is actually very important one. Maybe a more general question would be as follows: how to properly design an indexed collection of objects of different types (having a common superclass) with easy indexed access to objects of particular subtype? So, having a through index is a neccesity.

One can assume that all the types are known at compile-time, and amount of every particular object in the whole array is constant (from config file).

Upvotes: 0

Views: 168

Answers (2)

Dave
Dave

Reputation: 339

It sounds to me like you have separate objects and occasionally you need to iterate over all of them. Rather than making a confusing vector with subranges monster, just use separate vectors. When you need to iterate over all of them, just iterate over each one separately. Your code will be much cleaner that way.

Upvotes: 0

Bo Persson
Bo Persson

Reputation: 92241

If you really want to to this, you could have a class storing several std::vectors and then supply an operator[] for the class itself that redirects into these vectors, perhaps depending on their respective size.

While you're at it, the outer class could also provide begin() and end() to allow iteration over the entire dataset.

I doubt though that the good-design tag is applicable here. :-)

Upvotes: 3

Related Questions