Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
643 views
in Technique[技术] by (71.8m points)

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 it dosent sort ?

but if we had

 bool operator < (c1 w)
    {
        return number < w.number;
    }

and

vector<c1> vec = { ... }

it would have been sorted !

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The most straightforward approach is to define a 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 I would suggest is a generic functor to 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 with this, define the usual c1::operator< ( const c1 & ) and likewise for other classes.

Generally, best practice is to avoid pointers entirely, including arrays of pointers.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...