Passing a third argument to sort function of C++(STL)

♀尐吖头ヾ 提交于 2019-12-25 05:58:28

问题


Normally compare function of sort in c++ takes two arguments e.g:

sort(v.begin(),v.end(),compare);

bool compare(int a,int b)
.
.
.

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;

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?


回答1:


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


来源:https://stackoverflow.com/questions/15055606/passing-a-third-argument-to-sort-function-of-cstl

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!