C++函数对象(也称为仿函数或functor)在算法中扮演着非常重要的角色
<
进行比较。但是,有时我们需要使用自定义的比较逻辑。这时,我们可以创建一个函数对象作为比较器,并将其传递给算法。例如,std::sort
算法可以使用自定义的比较器对元素进行降序排序。#include <algorithm> #include <vector> struct CustomComparator { bool operator()(int a, int b) const { return a > b; } }; int main() { std::vector<int> vec = {3, 1, 4, 1, 5, 9}; std::sort(vec.begin(), vec.end(), CustomComparator()); return 0; }
#include <iostream> struct Fibonacci { int operator()(int n) const { if (n <= 1) return n; return fibonacci(n - 1) + fibonacci(n - 2); } private: int fibonacci(int n) const { if (n <= 1) return n; return fibonacci(n - 1) + fibonacci(n - 2); } }; int main() { Fibonacci fib; std::cout << "Fibonacci(10): " << fib(10) << std::endl; return 0; }
#include <iostream> #include <cmath> struct SquareRoot { double operator()(double x) const { return std::sqrt(x); } }; int main() { SquareRoot sqrt; std::cout << "Square root of 9: " << sqrt(9) << std::endl; return 0; }
总之,C++函数对象在算法中的作用主要是提供自定义的比较逻辑、传递状态信息和封装复杂操作。它们使我们可以更加灵活地使用STL算法,以满足不同的需求。