有两个STL向量,一个带有对象,第二个带有指向对象的指针。
v_objects = [obj1, obj2, obj3, obj4]
v_ptr = [ptr_to_obj1, ptr_to_obj2, ptr_to_obj3, ptr_to_obj4]
Vector v_ptr用于对v_objects中的元素进行排序。假设有些东西被添加到v_objects中,所以它看起来像:
v_objects = [obj1, obj2, obj3, obj4, obj5]
假设v_objects在插入后重新分配到其他地方,而v_ptr中的指针无效。现在我想使用v_ptr中的指针对对象进行排序,但它们无效。是否有可能创建一些巧妙的指针,指向与重新分配之前相同的对象(使用stl :: vector)?
答案 0 :(得分:4)
我不这么认为。你可以通过使用shared_ptr
s对象的单个向量来节省麻烦,或者只使用ptr_vector
。
答案 1 :(得分:3)
有几种方法可以解决这个问题:
v_objects
以存储指向对象的指针(这会使内存管理变得复杂,但使用智能指针可能有所帮助)。v_ptr
更改为将索引存储到v_objects
而不是指针。我个人的偏好是后者。
答案 2 :(得分:1)
我不完全理解你想做什么,但你可以将索引存储到容器中,而不是指针。用于排序的比较器函子将存储对向量的引用,并取消引用元素以获取值。
只要原始向量中元素的顺序没有改变(即只在末尾插入),索引向量仍然有效。如何处理新添加的元素,或者如果对原始矢量执行任何其他更改则是另一回事:
// 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 ) );