D
D
dalbio2020-06-10 13:48:27
C++ / C#
dalbio, 2020-06-10 13:48:27

Can you explain how a comparator works?

there is a comparator for set:

set<pair<int, int>,cmp>s;
struct cmp {
  bool operator() (const pair<int, int>& a, const pair<int, int>& b) const {
    int lena = a.second - a.first + 1;
    int lenb = b.second - b.first + 1;
    if (lena == lenb) return a.first < b.first;
    return lena > lenb;
  }
};

bool operator() is a special word or can be called anything, why does it get parameters as constants by reference (is it on purpose or can it be by value)?
And why const in this fragment?
const {
    int lena = a.second - a.first + 1;
    int lenb = b.second - b.first + 1;
    if (lena == lenb) return a.first < b.first;
    return lena > lenb;
  }

PS I am new to c++. I would be grateful for your help.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Armenian Radio, 2020-06-10
@dalbio

const is needed because if the comparator changes something in the container, the container will obviously go crazy. Professionals attach const (and even better - constexpr ) to any entity that should not change according to the logic of the algorithm.
References are passed for the simple reason that it saves you from calling the copy constructor and destructor, which can be extremely critical for some heavy objects, or will block compilation with a bunch of errors if the object does not allow itself to be copied

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question