Sorting a vector of custom objects

后端 未结 13 2930
既然无缘
既然无缘 2020-11-21 05:14

How does one go about sorting a vector containing custom (i.e. user defined) objects.
Probably, standard STL algorithm sort along with a predicate (a fu

13条回答
  •  不知归路
    2020-11-21 05:41

    You could use functor as third argument of std::sort, or you could define operator< in your class.

    struct X {
        int x;
        bool operator<( const X& val ) const { 
            return x < val.x; 
        }
    };
    
    struct Xgreater
    {
        bool operator()( const X& lx, const X& rx ) const {
            return lx.x < rx.x;
        }
    };
    
    int main () {
        std::vector my_vec;
    
        // use X::operator< by default
        std::sort( my_vec.begin(), my_vec.end() );
    
        // use functor
        std::sort( my_vec.begin(), my_vec.end(), Xgreater() );
    }
    

提交回复
热议问题