When do we use Functor and when do we use comparator?
Also, what is the difference between the two?
Functor vs Custom Comparator
hi @raghav6 ,
let me first discuss about comparators , some stl function like sort , lower_bound, binary_search, priority_queue uses comparisons(like greater than , smaller than , size, etc ) to compute some functionalities, now when we provide comparators to a stl function what happens is those comparisons are replaced with the comparators we provide, so instead of comparing elements through predefined operators, now the stl function uses comparators defined by the user to perform those comparisons, which gives us users the power to customize the fundamental functionality of the function.
Now, you can provide comparators to function mainly using two ways,
- Using a function
- Using a functor.
Now, you may think how will I know when to use function or functors, now it depends on the function definition, some function requires you to pass comparators in form of function (like sort, lower_bound,upper_bound,binary_search, etc) and some wants you to pass functors as comparators like (priority_queue, set, map, etc)
So, what you should do now is to try using comparators yourself, practice and try to customize different stl functions, with practice you will know how to use comparators,
In case you are not familiar with functors then I suggest you give a read to this post:-
In case of any doubt feel free to ask
Mark your doubt as RESOLVED if you got the answer
thank you for the detailed explanation @O17LPOLA020023, one more thing, is it that we use functors with the containers? and comparators with the algorithms ?
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.