Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::sort with custom comparator

Tags:

c++

sorting

In the following code, why do all three IntComparator(), IntComparator2 and IntComparator3 work as the 3rd parameter of the sort() function? Wouldn't they have different l-value function types? Based on https://en.cppreference.com/w/cpp/algorithm/sort it says

The signature of the comparison function should be equivalent to the following:

bool cmp(const Type1 &a, const Type2 &b);

which seems to match IntComparator2 better?

Also which one would be preferable? Third option seems much simpler and more intuitive.


#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>

struct IntComparator
{
  bool operator()(const int &a, const int &b) const
  {
    return a < b;
  }
};

bool IntComparator2 (const int &a, const int &b)
{
    return a < b;
}

bool IntComparator3 (int a, int b)
{
    return a < b;
}

int main()
{
    int items[] = { 4, 3, 1, 2 };
    std::sort(items, items+4, IntComparator());

    for (int n=0; n<4; n++) {
        std::cout << items[n] << ", ";
    }

    std::cout << "\n";

    int items2[] = { 4, 3, 1, 2 };
    std::sort(items2, items2+4, IntComparator2);

    for (int n=0; n<4; n++) {
        std::cout << items2[n] << ", ";
    }

    std::cout << "\n";

    int items3[] = { 4, 3, 1, 2 };
    std::sort(items3, items3+4, IntComparator3);

    for (int n=0; n<4; n++) {
        std::cout << items3[n] << ", ";
    }

    std::cout << "\n";

    return 0;
}
like image 802
BYS2 Avatar asked May 17 '19 09:05

BYS2


1 Answers

std::sort accepts a functor. This is any object that can be called (with the correct parameters). The function achieves this by using templates, like the following

template<typename Iter, typename Comp>
void sort(Iter begin, Iter end, Comp compare) { ... }

IntComparator1, 2, and 3 are all valid functors for this comparator, since they can all be called using operator() with 2 integers.

Also like you said, the third option is indeed usually more intuitive.

like image 167
MivVG Avatar answered Nov 02 '22 02:11

MivVG