Custom comparison operator for std::sort

In C++

I am storing a struct in an array and want to sort that array by one member of that struct

For Example

struct node
{
    int a, b, c;
};

node ar[500];

How do I write a custom operator for std::sort and sort the array ar according to the value a?

This would do

bool compare(const node &x, const node &y)
{
    return x.a < y.a;
}

Remember, (according to http://www.cplusplus.com/reference/algorithm/sort/)

  1. The boolean 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.
  2. It cannot modify any of its arguments.

You can read the following blog for more details.

http://fusharblog.com/3-ways-to-define-comparison-functions-in-cpp/

3 Likes

bool comp(node x,node y)
{
return x.a<y.a;
}

1 Like