Re: "Variable Depth" Problem



Kai-Uwe Bux wrote:

And I understand that you can create similar behavior in more strict
languages, like C++, by creating an array class whose members can
also be arrays, thereby allowing array-of-array-of-array-etc...

Not in C++. Instead you could do something like:

When you say "Not in C++," do you mean that you *can't* do that in C++
or that you *shouldn't* do that in C++ because it doesn't follow the
"spirit" of C++? If you mean the former, I have to disagree because
I've done it, more than once. I can post sample code if needed, but all
you have to do is create a class that contains a vector of pointers to
the same class. You can even make your arrays behave similarly to perl
arrays by having your class's [] operator perform an allocation when
invoked on a node that doesn't already exist. Then, syntax like this
becomes perfectly legal:

MyArrayOfArrayClass x;
x[2][3][4][5][6] = 7;

The array x now has six dimensions and (depending on how you define the
semantics of your [] operator) a total of 720 elements.

typedef std::vector< unsigned long > multi_index;
typedef std::map< multi_index, T > sparse_variable_dim_array_of_T;

This is interesting. You get a map with whatever element type you like,
with a key that is a vector. So how would you assign elements into your
map? I don't believe that C++ allows anything like this:

x[{1, 2, 3, 4, 5}] = 6;

Having to create and initialize a vector just to use it as an index
every time you want to access the map would be cumbersome:

std::vector key;
key.push_back(1);
key.push_back(2);
key.push_back(3);
key.push_back(4);
key.push_back(5);
x[key] = 6;

I suppose there's a more elegant way, maybe like this:

unsigned long indices[5] = {1, 2, 3, 4, 5};
std::vector key(indices, &indices[5]}; // (first, last) constructor
x[key] = 6;

It's still a bit awkward. Maybe it's possible to create a class with an
overloaded [] operator that could build the vector, then use it as the
look-up into the map, so that the above could be written as:

x[1][2][3][4][5] = 6;

It's not obvious to me how (if) that could be done, though.
.