Sorting strings and Overriding std::sort comparison

At that post, I try to illustrate one of the use case of comparison overriding for std::sort on top of a simple problem. Our problem is as follows:

Write a method to sort an array of strings so that all the anagrams are next to each other.

It seems very complicated at the first sight but if you know that little trick then it is very easy to grasp.

What we're gonna do is :

  1. sort each string chars in itself before comparison.
  2. compare each pair of strings.
  3. sort with that comparison.

The realization of the algorithm is below with clearing comments.

Share