Custom Sorting in C++:
As we can as always use the sort() function to sort a data in a fixed order. You can sort an array of integers in ascending order, you can sort a string.
But what if you want to sort with some custom rule, Here is what you can do.
Suppose you want to sort an array of strings so that all the anagrams are next to each other. You can use the custom sort function as follows. First, create a comparator, it will compare the elements as you want it to.
bool AnagramComparator(string s1, string s2){ | |
sort(s1.begin(), s1.end()); | |
sort(s2.begin(), s2.end()); | |
return s1 == s2; | |
} |
Now you can call the sort function as follows.
sort(arr, arr+n, AnagramComparator); | |
No comments:
Post a Comment