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

标签 c++ sorting vector std-pair

我有一对 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 .

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.

关于c++ - 带有第三个参数(即比较器函数)的重载 sort() 如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40559800/

相关文章:

javascript - 使用自定义顺序对字符串数组进行排序

C++ - 为什么插入类型的顺序会影响 Vector 性能 (GCC 4.81)

c++ - 我什么时候应该使用 std::thread::detach?

c++ - 全局环境照明?

c++ - vector::push_back 什么时候增加容量?

c++ - 将类型对列表的 vector 大小设置为用户在类中给定的大小

c - C 中字符串的排序列表数组

java - Arrays.sort() 与使用 map 排序

c++ - 为什么我得到的 deque 的 max_size() 小于 vector 的 max_size()?

c++ - 从 vector 范围中删除特定元素