Hi

I have just started using STL vectors and iterators so please excuse my ignorance. Suppose I have three classes A,B and C such that :

std::vector<A> aObjects
wherein each object "a" comprises a vector of "b" objects which in turn comprises a vector of "c" objects

ie.

class A{
...
std::vector<B> bObjects;

};

class B{
...
std::vector<C> cObjects;

};

class C{
...
float left,right;
};

I would like to assign an iterator to access the elements(objects) in the arrays aObjects,bObjects and cObjects when initialising the arrays: let's call these aIterator,bIterator,cIterator respectively, i.e.

std::vector<A>::iterator aIterator;
std::vector<B>::iterator bIterator;
std::vector<C>::iterator cIterator

.

I then create each instance of the respective object using

aObject.push_back(A constructor);

What is the best way to initialise the necessary bIterator and cIterator? In the constructor for A and B respectively

A::A{
// add all B objects to vector bObjects
bObjects.push_back(B());
// when finished adding B objects to bObject initialise bIterator
std::vector<B>:iterator =bObjects.begin();
}

How do I then dereference? e.g

aIterator->bIterator->cIterator->left

The alternative is to index the explicit elements i.e.

aObject[i].bObject[j].cObject[k].left

or similar

Thanks in advance

Mark

It sounds to me like you are making a design mistake. You shouldn't be permanently storing iterators you should create them when you need them they are essentially a temporary thing.

There is a good reason for this, for several of the containers under certain operations iterators can become invalid. For instance any operation that changes the capacity of a vector can invalidate all iterators into it.

Assuming you cant do something like std::vector<std::vector<std::vector<C> > > aObjects Then I would be tempted to write B something like

class B{
public:
    typedef std::vector<C>::iterator iterator;
    typedef std::vector<C>::const_iterator const_iterator;

    iterator begin ()
    {
        return cObjects.begin();
    }

    const_iterator begin () const
    {
        return cObjects.begin();
    }

private:
    ...
    std::vector<C> cObjects;
};

That is to make you B a container or something like a container. This also completely encapsulates the implementation of B, code using B does not need to know that B uses a vector.

You could implement other operators, such as operator[] as required or at() to allow direct access.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.