c++ - sort on a vector of pointers changes data in a copy of the vector? -
i have vector of pointers objects, , @ point, making second vector sub-elements of vector. now, sorting original vector changes elements in second vector (there different elements in after sort).
is expected behaviour? have make_indirect_iterator? there better solution (assuming want keep vector of pointers)?
std::vector<std::shared_ptr<myobj>> vecall; std::vector<std::shared_ptr<myobj>> vecsub; // fill vecall something... for(auto obj : vecall) { if( obj->x >=0 ) { vecsub.push_back(obj); } } // 3 objects in 'vecsub' std::sort(boost::make_indirect_iterator(vecall.begin()), boost::make_indirect_iterator(vecall.end()), std::greater<myobj>()); // there 3 different objects in 'vecsub'
yes, it's related make_indirect_iterator
. causes object values swapped, instead of reordering pointers.
you instead use normal iterators , perform dereference in comparison step. lambdas make easier:
typedef decltype(vecall.front()) iter; std::sort(vecall.begin(), vecall.end(), [](iter a, iter b) { return *a > *b; });
version reusable functor (thanks mooingduck suggestion):
struct indirect_greater { template<typename iter> bool operator()(iter a, iter b) const { return *a > *b; } }; std::sort(vecall.begin(), vecall.end(), indirect_greater());
c++14 adds polymorphic lambdas, let write short lambda [](a, b)(*a > *b)
behaves second (functor) solution. no need name iterator type (e.g. decltype
).
Comments
Post a Comment