Custom Comparators in C++

Custom Comparators are used to compare the members or objects of user-defined containers (class/data structure). For example:
Consider a struct Node,

struct Node {
    int i;
    char ch;
};

Note
Structures (also called structs) are a way to group several variables into a single data structure. Each variable in the structure is known as a member of the structure.
A structure unlike vectors can contain members of different data types (int, char, etc.)

Now, let’s create a custom comparator for struct Node:

//Custom comparator 
bool cmp (const Node &a, const Node &b){
    return a.i < b.i;
}

The above comparator method cmp() take two members of struct Node (a & b) and return true if
(int) i of a < (int) i of b or a.i < b.i

And, the above custom comparator cmp when passed to the C++ STL sort method to sort an array of Node: Node a[3];
will sort the members of array a[] in a way such that ai will appear before aj in sorted a[] if:
ai.i < aj.i

int N = 3;

Node a[N];
a[0].i = 2;
a[0].ch = 'b';
a[1].i = 1;
a[1].ch = 'a';
a[2].i = 3;
a[2].ch = 'c';

sort(a, a+N, &cmp);

for (int i=0; i<N; i++) {
  cout<<a[i].i<<" "<<a[i].ch<<endl;
}

Output

1 a
2 b
3 c

Here’s a working example: Ideone

These are some articles utilising Custom Comparators:

  • Array Manipulation | HackerRank
    Starting with a 1-indexed array of zeros and a list of operations, for each operation add a value to each the array element between two given indices, inclusive. Once all operations have been performed, return the maximum value in the array.
  • C++ Standard Template Library (STL) – [Linked List]
    The C++ Standard Template Library (STL) is a powerful library of C++ template classes that provide general-purpose classes and functions. 
  • Activity Selection problem
    Activity selection problem is the problem of selecting the largest set of mutually exclusive activities.

Leave a Reply