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

I want to sort an array of objects class Personbased on its data member age. I store objects in vector<Person> v.

As I understand it, there can be at least 4 ways to perform this action, and I have the following questions based on the methods described below.

  • How does it work operator()inside a class? Should I not overload the '<' operator here? Why '()'?

  • I sent the object as the third parameter in method 1. But in method 2, I sent the name of the function. Why is this so?

  • Which of the four methods is the best? I felt that method 3 was the simplest.

Method 1

class cmp
{
public:
    bool operator() (  Person const &a,  Person const &b )
    {
        return a.age < b.age ;
    }
};

sort( v.begin(), v.end(), cmp());

Method 2

bool cmp( const Person a, const Person b ) 
{
    return a.age < b.age ;
}

sort( v.begin(), v.end(), cmp );

Method 3

bool operator < ( const Person a, const Person b )
{
    return a.age < b.age ;
}

sort( v.begin(), v.end());

Method 4

//using lambda expression
sort( v.begin(), v.end(), [](const Person &a, const Person &b){return a.age < b.age;});
+4
4

std::sort ( , ), , , ( ) .

std::sort : operator<, /. :— , <, /.

?

, . , operator<, , , . , .

, . , operator< . , , : , ; ( ), ; , , , , , .

, , int :

 std::vector<int>  v{10, 3, 12, -26};
 std::sort(v.begin(), v.end());
 print(v);

: -26,3,10,12. operator< .

, , (, ), :

 std::vector<int>  v{10, 3, 12, -26};
 auto abs_cmp = [](int a, int b) { return std::abs(a) < std::abs(b); };
 std::sort(v.begin(), v.end(), abs_cmp);
 print(v);

: 3,10,12,-26. , .

, .

+4

i. void sort( RandomIt first, RandomIt last ); , , operator<. 3 .

template< class RandomIt >
void sort( RandomIt first, RandomIt last )
{
    ...

    if (*i < *j)
      ....

    ...
}

 

ii. void sort( RandomIt first, RandomIt last, Compare comp ); , , operator<.

template< class RandomIt, class Compare >
void sort( RandomIt first, RandomIt last, Compare comp )
{
    ...

    if (comp(*i, *j))
      ....

    ...
}

1,2,4 . (). 1 cmp(), operator(), . 2 4 , ().

+4

() ? '<' ? '()'?

operator() - . cmp , . sort .

1. 2 . ?

cmp . .

? , 3 .

3 , , . , ? operator< Person, . , , Person.

2 , , 1 4. - 1, , sort .

4 , , , sort , .

1 , ++ 03 ( 4). 4 1. 1 , . , ( , auto).

+2
  • , , () .
  • As far as I know, sorting takes functions, functions, and lambda expressions to use them to compare objects.
  • In method 3, you do not provide a functor, function, or lambda expression for comparison, so by default it is sorted using the standard <operator. Obviously, it does not sort Person objects by age, as you would like. In my opinion, the purest form is method 4 using the lambda expression.
+1
source

All Articles