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

问题描述 投票:1回答:1

我有一对矢量:

vector<pair<char,int> > pAB;

我用sort函数命令它。 sort函数有第三个参数(可能是一个返回布尔值或布尔值的函数)因为我决定按升序排序。为此你需要这个sortbysec函数:

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

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

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

我想知道为什么会这样。

注意:我已经在互联网上寻找它没找到任何东西。

c++ sorting vector std-pair
1个回答
1
投票

sort函数自动为ab分配一对。

您使用的函数(此处为sortbysec)需要返回类型为Boolean

通过以这种方式定义它:

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

,当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.
© www.soinside.com 2019 - 2024. All rights reserved.