Vector trouble

Hi

I have created a class (call it class B) that has a data member of a pointer to an object of a different class(call it class A) (to avoid the overhead of each class B object holding a class A object itself). For example:

class A{ // N.b. the actual class has a much larger memory size than this example

int j;

};

class B{

A* pointerToObjectOfClassA

};

The problem is that I would like to hold objects of class A in an STL vector so that I can avoid having to manage the memory myself. But then how would I reference a specific object held in this vector within class B

A vector iterator wouldn't work as it could become invalid if the vector was changed.

The only thing I could think of was for class B to hold a pointer to the vector of class A objects and an identifying ID (and corresponding unique ID held in class B objects). But this would then involve a search of the vector to find the object with the matching ID and I need to avoid this overhead. Obviously I could use an STL map or such like if I went for this option, but maybe there's an easier and better solution I'm missing.

Any help greatly appreciated.


Thank you,

Sean.



Answer this question

Vector trouble

  • mcgin1591

    Instead of using a vector<A>, which would cause the objects to be copied quite frequently, you should look to smart pointer classes such as those of boost. vector<boost::smart_ptr<A>>. Your B instances can then hold copies of the smart_ptr<A>. When all references to an A is removed, the object is destroyed, and you will not have any issues with iterator invalidation (since the vector will hold pointers, not objects).

  • adisciullo

    I think that the idea of using a STL map is reasonable. The STL map class is quite efficient. If you need to optimize it, there are ways to optimize it and hopefully you can do that when you know what to optimize for. An important criteria is volatility. If updates are infrequent but access is frequent, then it might be useful to spend time developing a more efficient solution. Your time however is a consideration. The STL map class can probably handle volatility and access to the data more efficiently than anything you can write.

    I am not an expert however; if someone else says that something else is more efficient, then they are probably correct.

    The CLR uses handles for it's objects and perhaps you can use a handle for an object instead of a pointer.



  • thomas_woelfer

    Simple Samples wrote:

    The STL map class can probably handle volatility and access to the data more efficiently than anything you can write.

    If updates and lookups are mixed, a map class will yield better performance than the vector. If, however, items are put there as part of an initialization procedure, and then merely looked up; a sorted vector is likely to be quicker.



  • Vector trouble