Reputation: 1155
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?
Upvotes: 0
Views: 2008
Reputation: 44258
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 ) );
Upvotes: 5