0

Does name_compare() calls the default construction or the operator() of class name_compare in sort(vs.begin(), vs.end(), name_compare());?

I think it's the first one.Am i right?

I would be thankful for any hint on this question.

 struct Record {
        string name;
        // ...
    };
    struct name_compare {   // compare Records using "name" as the key
        bool operator()(const Record& a, const Record& b) const
            { return a.name<b.name; }
    };
    void f(vector<Record>& vs)
    {
        sort(vs.begin(), vs.end(), name_compare());
        // ...
    }   
Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982
sunshilong369
  • 646
  • 1
  • 5
  • 17
  • the operator() can't be called without an object. It isn't a static function and it can't be static either. – asmmo May 23 '20 at 10:03

1 Answers1

2

In this call

sort(vs.begin(), vs.end(), name_compare());

there is created a temporary object of the type name_compare as a function argument using the default constructor. Within the function std::sort there is called the operator function of the object.

Here is a demonstrative program

#include <iostream>
#include <string>

struct Record
{
    std::string name;
};

struct name_compare 
{
    name_compare()
    {
        std::cout << "name_compare() is called\n";
    }

    bool operator()( const Record &a, const Record &b ) const
    {
        std::cout << "operator () is called\n";
        return a.name<b.name; 
    }
};

int main() 
{
    Record a = { "A" };
    Record b = { "B" };

    if ( name_compare()( a, b ) ) std::cout << a.name << " is less than " 
                                            << b.name << '\n';


    return 0;
}

Its output is

name_compare() is called
operator () is called
A is less than B

In this expression

name_compare()( a, b )

there called constructor creating a temporary object

name_compare()( a, b )
^^^^^^^^^^^^^^

and then there is called the operator function of the created object

name_compare()( a, b )
              ^^^^^^^^

To make it more clear you can rewrite the expression the following way

name_compare().operator ()( a, b )
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • Thank you for your clarification.I wonder that if the temporary object(`name_compare()`) is passed by value or by reference to `std::sort`. – sunshilong369 May 23 '20 at 10:07