在C基准传递STD交易算法predicates ++ [英] Pass std algos predicates by reference in C++

查看:243
本文介绍了在C基准传递STD交易算法predicates ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想删除从的std ::列表元素和保留已删除元素的一些统计数据。

I am trying to remove elements from a std::list and keep some stats of deleted elements.

为了做到这一点,我使用的remove_if函数从列表中,我有一个predicate。我想用这个predicate收集统计信息。这里是code为predicate:

In order to do so, I use the remove_if function from the list, and I have a predicate. I would like to use this predicate to gather statistics. Here is the code for the predicate:

  class TestPredicate
  {
  private:
    int limit_;

  public:
    int sum;
    int count;
    TestPredicate(int limit) : limit_(limit), sum(0), count(0) {}

    bool operator() (int value) 
    {
      if (value >= limit_)
      {
        sum += value;
        ++count;       // Part where I gather the stats
        return true;
      }
      else
        return false;
    }
  };

这里是code的算法中:

And here is the code for the algo:

std::list < int > container;
container.push_back(11);
TestPredicate pred(10);
container.remove_if(pred)
assert(pred.count == 1);

不幸的是,断言是假的,因为predicate是按值传递。有没有办法迫使它通过引用传递?

Unfortunately, the assertion is false because the predicate is passed by value. Is there a way to force it to be passed by reference ?

推荐答案

传递引用包装,可以从&lt;功能&GT;

Pass a reference wrapper, available from <functional>:

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


如果你只有C ++ 98/03,但你的编译器有TR1,您可以使用&LT; TR1 /功能&GT; STD: :TR1 :: REF 如果你犯了一个小的修改你的predicate:


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));

这篇关于在C基准传递STD交易算法predicates ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆