前闭后开区间表示法[ )

任何一个STL算法,都需要获得由一对迭代器(泛型指针)所标示的区间,用以表示操作范围。这一对迭代器标示一个前闭后开区间,以[first, last)表示。

function call操作符(operator())

所谓仿函数(functor)就是使用起来像函数一样的东西。如果针对某个class进行operator()进行重载,它就成为一个仿函数。

  1. #include <iostream>
  2. using namespace std;
  3. template <class T>
  4. struct plus {
  5. T operator()(const T& x, const T& y) const {return x + y;}
  6. };
  7. template <class T>
  8. struct plus {
  9. T operator()(const T& x, const T& y) const {return x - y;}
  10. };
  11. int main()
  12. {
  13. plus<int> plusobj;
  14. minus<int> minusobj;
  15. //就像使用一般函数一样,定义析构函数只是在构造对象的时候被调用起来,这个是随时都可以调
  16. cout << plusobj(3, 5) << endl;
  17. cout << minusobj(3, 5) << endl;
  18. //直接产生仿函数的临时对象(第一对小括号)。并调用之(第二对小括号)
  19. cout << plus<int>()(43, 50) << endl;
  20. cout << minus<int>()(43, 50) << endl;
  21. }

One advantage of functors over function pointers is that they can hold state. Since this state is held by the instance of the object it can be thread safe (unlike static-variables inside functions used with function pointers). The state of a functor can be initialized at construction. For instance, OEChem’s OEHasAtomicNum functor takes an argument on construction which defines which atomic number is required for the functor to return true. The state of a functor can also change during the operator() function. One group of functors, called accumulators, sum a value each time they are called. Finally, functors can take advantage of all of the other properties of C++ classes. A programmer can define any number of other functions which manipulate or query the state of the functor.

这里的保存state,是因为在创建object之后,就可以使用object中的成员进行状态的维护,而对于传统的采用传递函数指针的方式只能采用static变量来维护状态,仿函数能够确保线程安全。