Search code examples
sortingcomparesubscript-operator

what does the subscript operator mean in sort compare function?


struct pair{
    int first;
    int second;
}
vector<pair> v;
sort(v.begin(), v.end(), [](pair p1, pair p2){return p1.first < p2.first});

what does the [](pair p1, pair p2){return p1.first < p2.first} mean in sort? function pointer or anything else? I can't figure out the keywords to search.


Solution

  • this is a lambda expresion. See example below:

    void abssort(float* x, unsigned n) {
        std::sort(x, x + n,
            // Lambda expression begins
            [](float a, float b) {
                return (std::abs(a) < std::abs(b));
            } // end of lambda expression
        );
    }
    
    1. reference: https://msdn.microsoft.com/en-us/library/dd293608.aspx

    the function that is being passed as a parameter does not have a "function name" - it is anonymous. This is a useful abstraction as all that is needed is the functionality that is being passed (the name does not matter).