Avatar ·

What are functors in C++ and why are they needed?

Hello! I'm learning C++ and came across the term "functor". I read that it's something like an object that behaves like a function. But I don't quite understand why this is needed if there are regular functions and function pointers. For example, I know that you can pass a function to `std::sort` as a comparator: ```cpp bool compare(int a, int b) { return a < b; } std::sort(vec.begin(), vec.end(), compare); ``` But why use an object with an overloaded `operator()`? What's the advantage? I've heard that functors can store state, but I don't understand how to apply this in practice. Can you explain with a simple example where a functor is actually more convenient than a regular function? And another question: are functors the same as lambda expressions? Or are they different things? I would appreciate a detailed explanation.