Sorting a vector of custom objects

后端 未结 13 2939
既然无缘
既然无缘 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:51

    You are on the right track. std::sort will use operator< as comparison function by default. So in order to sort your objects, you will either have to overload bool operator<( const T&, const T& ) or provide a functor that does the comparison, much like this:

     struct C {
        int i;
        static bool before( const C& c1, const C& c2 ) { return c1.i < c2.i; }
     };
    
     bool operator<( const C& c1, const C& c2 ) { return c1.i > c2.i; }
    
     std::vector values;
    
     std::sort( values.begin(), values.end() ); // uses operator<
     std::sort( values.begin(), values.end(), C::before );
    

    The advantage of the usage of a functor is that you can use a function with access to the class' private members.

提交回复
热议问题