PROBLEM:
I want to set up a system of elements, while at the same time keeping pairs of these elements that I want to access and modify easily (add more).
At the same time, I want to keep the complexity to a minimum, and not implement everything in one class.
I decided to store the indices to the pairs using a struct, which can handle a large amount of the complexity of calculations among B's.
class A {
class B_pair {
int idx_of_B[2];
public:
B get_B_value_1(); // how to access B's?
B get_B_value_2();
// a lot more member functions
};
public:
std::vector<B> B_values;
std::vector<B_pair> special_B_pairs;
// a lot more stuff
};
However, I have the problem that I cannot access the B values from within the B_pair class.
FAILED SOLUTION 1
class A {
A() { B_pair::outer = this; }
class B_pair {
static A *outer;
void init_outer(A *o);
};
}
I used a static
member because I have a lot of B_pair
objects, and the extra memory of a pointer/reference in each is significant.
This works fine. However, if I have more than one A objects at the same time, then it is problematic, as the outer
pointer ends up pointing at the last created A
object.
FAILED SOLUTION 2
Another approach I took was storing pointers.
class A {
class B_pair {
B *items[2];
};
std::list<B> B_values; // I need random access iterators!!
};
However, this means that I need to use more inefficient data structures than std::vector
, which invalidates its iterators when it expands.
QUESTION
How could I access the members of the outer class A
from the inner class B
, or something similar to make this work? Ideally, I would like something similar to the first solution, but with one instance of A *outer
for each A
object.
Note that THIS IS POSSIBLE IN JAVA!!
P.S. At the moment I am using the Singleton design pattern, and kept the static pointer. Not a big fan of this solution.