开发者

STL vector and pointers to elements of vector

There are two STL vectors, o开发者_开发百科ne with objects and second with pointers to objects.

v_objects = [obj1, obj2, obj3, obj4]
v_ptr = [ptr_to_obj1, ptr_to_obj2, ptr_to_obj3, ptr_to_obj4]

Vector v_ptr is used to sort elements in v_objects. Let's say that something is added to v_objects so it looks like:

v_objects = [obj1, obj2, obj3, obj4, obj5]

Let's say that v_objects are after insertion reallocated somewhere else and pointers in v_ptr are invalid. Now I want to sort objects using their pointers in v_ptr, but they are invalid. Is it somehow possible to create some clever pointers which point to the same object as they were before reallocation (using stl::vector)?


I don't think so. You could probably save yourself the trouble by just using a single vector with shared_ptrs to your objects, or just use a ptr_vector.


There are several ways to tackle this:

  1. You could change v_objects to store pointers to objects (this will complicate memory management, but using smart pointers might help).
  2. You could change v_ptr to store indices into v_objects instead of pointers.

My personal preference would be the latter.


I don't fully understand what you want to do, but you could store indices into the container, rather than pointers. The comparator functor for the sorting would store a reference to the vector and dereference the elements to obtain the values.

As long as the order of the elements in the original vector does not change (i.e. only insertions at the end) the vector of indices would still be valid. What to do with the newly added elements, or if any other change is performed on the original vector is a different story:

// sketch (reorganize code as needed):
std::vector< type > original = load();
struct compare_indexed {
   std::vector< type > const & v;
   compare_indexed( std::vector< type > const & v ) : v(v) {}
   bool operator()( int lhs, int rhs ) const {
      return v[lhs] < v[rhs];
   }
};
// Create original index vector
std::vector< int > indices;
for ( unsingned int i = 0; i < original.size(); ++i ) {
   indices.push_back( i );
}
std::sort( indices.begin(), indices.end(), compare_indexed( original ) );
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜