Pass std algos predicates by reference in C++

流过昼夜 提交于 2019-12-05 02:43:14

Pass a reference wrapper, available from <functional>:

container.remove_if(std::ref(pred));

If you only have C++98/03 but your compiler has TR1, you can use <tr1/functional> and std::tr1::ref if you make a small amendment to your predicate:

#include <tr1/functional>

class TestPredicate : public std::unary_function<int, bool>
{                 //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  // ...
}

container.remove_if(std::tr1::ref(pred));

If all else fails, then you can hack up a manual solution with relative ease:

struct predref
{
  TestPredicate & p;
  bool operator()(int n) { return p(n); }
  predref(TestPredicate & r) : p(r) { }
};

container.remove_if(predref(pred));

The functors passed to the algorithms can be copied inside the algorithm an indeterminate number of times, so you cannot store state directly in the functor. You can, on the other hand, store the state outside of the functor, by using a pointer or reference to some external state structure.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!