我有一对 vector :
vector<pair<char,int> > pAB;
我用排序功能订购了它。排序函数有第三个参数(可能是返回 bool 值的函数或 bool 值本身),因为我决定按升序对其进行排序。为此你需要这个 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
函数自动为 a
分配一个对和 b
.
您使用的函数(此处为 sortbysec
)需要具有 Boolean
的返回类型.
这样定义:
bool sortbysec(const pair<char,int> &a, const pair<char,int> &b){
return (a.second < b.second);
}
,vector 中的 pairs 根据 second
降序排列每对的值,当(a.second < b.second)
是true
.
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.
关于c++ - 带有第三个参数(即比较器函数)的重载 sort() 如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40559800/