C++ STL - How does the third argument of the STL sort() work?

后端 未结 4 1886
傲寒
傲寒 2020-12-18 01:14

I wish to sort an array of objects of class Person on the basis of its data member \'age\'. I store the objects in a vector v

4条回答
  •  死守一世寂寞
    2020-12-18 01:43

    The sort function has two overloads

    i. void sort( RandomIt first, RandomIt last ); It doesn't accept compare function, it expects the items have operator< defined. You'r method 3 uses this overload.

    template< class RandomIt >
    void sort( RandomIt first, RandomIt last )
    {
        ...
    
        if (*i < *j)
          ....
    
        ...
    }
    

     

    ii. void sort( RandomIt first, RandomIt last, Compare comp ); it accepts a compare function, it's useful when your items don't have operator< defined.

    template< class RandomIt, class Compare >
    void sort( RandomIt first, RandomIt last, Compare comp )
    {
        ...
    
        if (comp(*i, *j))
          ....
    
        ...
    }
    

    Methods 1,2,4 use this overload. All the passed third arguments can be called by (). Method 1, sends an object by cmp(), this object has overloaded operator() and above code invokes it. Method 2 and 4, sends pointer to functions and a pointer to a function can be invoked by ().

提交回复
热议问题