2016-11-12 37 views
1

我有一个对一个矢量:带有第三个参数(即比较函数)的重载排序()如何工作?

vector<pair<char,int> > pAB; 

i相排序功能下令。 sort函数有第三个参数(可能是一个返回布尔值或布尔值本身的函数),因为我决定按升序排列。为此你需要这个sortbysec funtion:

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

,当我用这个功能我没有传递一个参数:

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

我想知道为什么这个工作。

注:我已经看它互联网上没有发现任何

+1

“我没有送一个参数:” - 你叫什么做的第三个“东西”你送到'的std :: sort'?如果你问为什么'std :: sort(pAB.begin(),pAB.end())'(代码没有显示)可以工作,那是因为[有一个'运算符'''重载'std :: pair <>'](http://en.cppreference.com/w/cpp/utility/pair/operator_cmp)由标准库提供,默认比较器是['std :: less'](http:// en .cppreference.com/w/cpp/utility/functional/less),调用.. – WhozCraig

+2

查找函数指针。 – Peter

回答

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. 
+1

我认为问题是关于函数指针的存在:如何将函数本身作为参数传递? –

相关问题