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:
operator()
Use a lambda expression when:
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
Answers to questions are automatically generated and may not have been reviewed.
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.