带有第三个参数(即比较器函数)的重载 sort() 如何工作?

How does a overloaded sort() with a third parameter (i.e. comparator function) work?

我有一对向量:

vector<pair<char,int> > pAB;

我用排序功能订购了它。排序函数有第三个参数(可能是 return 一个布尔值或布尔值本身的函数),因为我决定按升序对其进行排序。为此你需要这个 sortbysec 函数:

bool sortbysec(const pair<char,int> &a,
         const pair<char,int> &b){   
         return (a.second < b.second);}

当我使用这个函数时,我不必发送参数:

 sort(pAB.begin(),pAB.end(),sortbysec);

我想知道为什么会这样。

注意:我已经在网上找过了,没找到。

sort 函数自动将 分配给 ab

您使用的函数(这里是sortbysec)需要有一个return类型的Boolean

这样定义:

bool sortbysec(const pair<char,int> &a, const pair<char,int> &b){   
   return (a.second < b.second);
}

,当(a.second < b.second)true.

时,vector中的对根据每对的second值降序排列

More info:

void sort (RandomAccessIterator first, RandomAccessIterator last, Compare comp);

comp
    Binary function that accepts two elements in the range as arguments, 
    and returns a value convertible to bool. The value returned indicates whether the 
    element passed as first argument is considered to go before the second in the specific 
    strict weak ordering it defines.The function shall not modify any of its arguments.
    This can either be a function pointer or a function object.