sorting - C++ how to sort vector<class *> with operator < -
i have
class c1{ public: int number; c1() { number=rand()%10; } bool operator < (c1 *w) { return number < w->number; } }; vector<c1*> vec = { ... } sort(vec.begin(),vec.end()) why dosent sort ?
but if had
bool operator < (c1 w) { return number < w.number; } and
vector<c1> vec = { ... } it have been sorted !
the straightforward approach define function
bool c1_ptr_less( c1 const *lhs, c1 const *rhs ) { return lhs->something < rhs->something; } std::sort( vec.begin(), vec.end(), & c1_ptr_less ); what suggest generic functor take care of all pointer arrays
struct pointer_less { template< typename t > bool operator()( t const *lhs, t const *rhs ) const { return * lhs < * rhs; } }; std::sort( vec.begin(), vec.end(), pointer_less() ); armed this, define usual c1::operator< ( const c1 & ) , likewise other classes.
generally, best practice avoid pointers entirely, including arrays of pointers.
Comments
Post a Comment