简体   繁体   中英

About the comparison function object of std::sort

In the following two examples: example 1:

struct less_than_key
{
    inline bool operator() (const MyStruct& struct1, const MyStruct& struct2)
    {
        return (struct1.key < struct2.key);
    }
};

std::vector < MyStruct > vec;

vec.push_back(MyStruct(4, "test"));
vec.push_back(MyStruct(3, "a"));

std::sort(vec.begin(), vec.end(), less_than_key());  //LINE1

Example 2:

std::array<int, 10> s = {5, 7, 4, 2, 8, 6, 1, 9, 0, 3}; 
struct {
    bool operator()(int a, int b)
    {   
        return a < b;
    }   
} customLess;
std::sort(s.begin(), s.end(), customLess);        //LINE2

Why the compare function object at LINE1 has "()", ie, less_than_key()? The compare function object at LINE2 does not have "()", ie, customLess?

Line 1 has parentheses because it's making an instance of the less_than_key class and passes it as a parameter (ie it's making a value).

Line 2 doesn't have parentheses because it already is an instance of the anonymous struct provided (ie it's already a value).

std::sort expects an instance of the comparator object to work, which is why you can sometimes construct them in place or provide one that is already constructed.

In the example 1 you are declaring a struct called less_than_key, but you don't have any instance of this struct, you have only a declaration. In LINE 1 you are calling the constructor of the struct and creating an instance of the object to be used by std::sort function.

In the example 2 it is different. You are also declaring a struct, this time without name (anonymous), but the difference is that you are creating an instance "customLess" of this type (calling the constructor implicitly). So, as you already have the instance created, you don't need to create it in the std::sort function.

Look at the difference in the declaration of the structs:

1.- struct less_than_key { ... };

2.- struct [some_name_if_wanted] { ... } customLess ;

std::sort expects a comparison function object . In the first example, you're constructing a object. In the second example, you already have one. The easiest example would be to look at the transparent comparators, ie std::less<>() , which is a class template.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM