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

后端 未结 4 1873
傲寒
傲寒 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:27

    How does operator() defined inside a class work? Should I not overload the '<' operator here as well? Why '()' ?

    operator() is the function call operator. Instances of your class cmp are callable in the same way that a function is callable. The call is required by sort to perform the necessary comparison.

    I sent an object as the 3rd parameter in method 1. But, in method 2, I sent the name of a function. Why is it like that?

    Instances of cmp are callable. Function names are callable.

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

    The main disadvantage of 3 is that you have defined that one Person is less than or greater than another Person according to their ages. What if you want to sort them by name elsewhere? You've already defined operator< for Person, so you can't do the same trick again. All three of the other methods define a comparison for use in a specific sort, rather than defining what it means in general to compare Person.

    The main disadvantage of 2 is that it's somewhat harder for the compiler to inline than 1 or 4. It doesn't really have any advantages over 1, but for completeness it's nice that sort can take a function pointer.

    The main advantage of 4 is that if you only use the comparison once, it's often nicer to have it right there in the same line of code that calls sort, instead of being off somewhere else in the file.

    The main advantage of 1 is that it works in C++03 (unlike 4). 4 is more-or-less a new syntax for 1. 1 also has the advantage that it makes the comparator available for other code to use with the same name. You could achieve that with a lambda too if you wanted (you name a lambda by assigning it to an auto variable).

提交回复
热议问题