Functors vs Lambda Expressions
When should I use a functor instead of a lambda expression in C++?
Both functors and lambda expressions allow you to define callable objects in C++. However, there are situations where one may be preferred over the other:
Use a functor when:
- You need to maintain state across multiple calls
- You require the callable to have a specific type (e.g., for template specialization)
- You need to define multiple overloads of the
operator()
- You want to take advantage of class features like inheritance or member functions
Use a lambda expression when:
- You need a simple, one-off callable without extra overhead
- You don't need to maintain state across calls
- You want to capture variables from the surrounding scope
For example, a functor is a good choice for a custom comparator in a sorting algorithm, as it can maintain state and provide a specific type:
#include <algorithm>
#include <iostream>
#include <vector>
class CustomCompare {
public:
CustomCompare(int t) : threshold(t) {}
bool operator()(int a, int b) const {
return (a > threshold) && (a < b);
}
private:
int threshold;
};
int main() {
std::vector<int> vec{1, 5, 2, 4, 3};
std::sort(
vec.begin(), vec.end(), CustomCompare(3));
for (int i : vec) {
std::cout << i << " ";
}
std::cout << "\n";
}
1 5 2 4 3
On the other hand, a lambda is better suited for a simple, one-time operation:
#include <iostream>
#include <algorithm>
#include <vector>
int main() {
std::vector<int> vec {1, 2, 3, 4, 5};
auto it = std::find_if(vec.begin(), vec.end(),
[](int i){ return i > 3; });
std::cout << *it << "\n";
}
4
Function Objects (Functors)
This lesson introduces function objects, or functors. This concept allows us to create objects that can be used as functions, including state management and parameter handling.