传递第三个参数到C ++的排序函数(STL) [英] Passing a third argument to sort function of C++(STL)
本文介绍了传递第三个参数到C ++的排序函数(STL)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在c ++中 sort
的通常比较函数需要两个参数,例如:
Normally compare function of sort
in c++ takes two arguments e.g:
sort(v.begin(),v.end(),compare);
bool compare(int a,int b)
.
.
.
但是在向量中我已经存储了一个数组, / code>基于特定索引的向量。 viz:
But in the vector I have stored an array and I want to sort
the vector based on a particular index. viz:
int arr[3];
vector<arr> v;
如果我想基于索引0或1或2对v进行排序,取决于用户的输入)?这里的问题是,当我将写入比较函数:
How can I use sort function if I want to sort v based on index 0 or 1 or 2(depending on user's input)? Here problem is that when I will write compare function:
bool compare(int *arr,int *arr1)
那么我怎么能告诉这个函数根据特定的索引排序?
then how can I tell this function to sort on the basis of a particular index?
推荐答案
只需使用functor对象:
Just use functor object:
struct coord { int *arr; };
struct Comparer : std::binary_function<coord,coord,bool> {
Comparer( int base ) : m_base( base ) {}
bool operator()( const coord &c1, const coord &c1 )
{
return c1.arr[m_base] < c2.arr[m_base];
}
private:
int m_base;
};
//...
std::sort( v.begin(), v.end(), Comparer( 1 ) );
这篇关于传递第三个参数到C ++的排序函数(STL)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文