​ 很多STL算法都使用函数对象——也叫函数符(functor)。

​ 函数符是可以以函数方式与()结合使用的任意对象,包含:函数名指向函数的指针重载了()运算符的类对象

#include <iostream>

class Linear
{
private:
    double slope;
    double y0;
public:
    Linear(double sl_ = 1, double y_ = 0)
        : slope(sl_), y0(y_) {}
    double operator()(double x) { return y0 + slope * x; }
};

int main()
{
    Linear f1;
    Linear f2(2.5, 10.0);
    double y1 = f1(12.5); // = f1.operator()(12.5) = 0 + 1 * 12.5
    double y2 = f2(0.4);  // = f1.operator()(0.4) = 10.0 + 2.5 * 0.4
    std::cout << y1 << "  " << y2 << std::endl;
    return 0;
}

​ 如上所示,能通过重载()运算符使得能够像调用函数那样使用Linear对象。

inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_SINCE_CXX20 _Function for_each(_InputIterator __first, _InputIterator __last, _Function __f) {
  for (; __first != __last; ++__first)
    __f(*__first);
  return __f;
}

​ 如STL的for_each函数,第三个参数就可以是函数符。

#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
#include <cmath>

int main()
{
    const int LIM = 5;
    double arr1[LIM] = {36, 39, 42, 45, 48};
    std::vector<double> gr8(arr1, arr1 + LIM);
    std::ostream_iterator<double, char> out(std::cout, " ");
    std::transform(gr8.begin(), gr8.end(), out, static_cast<double(*)(double)>(std::sqrt));
    return 0;
}

​ 可以使用std::transform将容器中数据用std::sqrt计算并输出到控制台中。

template <class _Key, class _Tp, class _Compare = less<_Key>,
          class _Allocator = allocator<pair<const _Key, _Tp> > >
class _LIBCPP_TEMPLATE_VIS map

​ 最后,如std::map中第三个参数less<_Key>也是函数对象。

image-20240312003347627.png

​ 注:更多STL预设的模版类函数对象见<functional>头文件。

最后修改:2024 年 03 月 12 日