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

时间:2016-11-12 05:12:59

标签: c++ sorting vector std-pair

我有一对矢量:

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);

我想知道为什么会这样。

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

1 个答案:

答案 0 :(得分:1)

The sort function automatically assign a pair to both a and b.

The function you use (here, sortbysec) needs to have a return type of Boolean.

By defining it in this way:

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

, pairs inside vector are sorted in descending order based on second value of each pair, when (a.second < b.second) is 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.