2

我有一个带有访问器成员函数的类,我想调用它并将结果应用到使用 std::for_each 的仿函数。我在下面有一个使用 for 循环和 for_each 的工作版本,但 for_each 版本既神秘又麻烦。考虑到我可以使用 boost 而不是 C++11,有没有办法可以使 for_each 版本更简洁?

#if 0
   // for loop version:
   for(value_vector_type::iterator it = values.begin(); it!=values.end(); it++){
     avg(it->getValue());  // I want to put this in a for_each loop
   }
#else
  //  bind version:
  std::for_each(values.begin(), values.end(), // iterate over all values
    boost::bind(
      boost::mem_fn(&average_type::operator()), // attach the averaging functor to the output of the getvalue call
      &avg, 
      boost::bind(
        boost::mem_fn(&value_wrapper_type::getValue), // bind the getValue call to each element in values
        _1
      )
    )
  );
#endif    

这是完整的工作实现:

#include <vector>
#include <algorithm>
#include <iostream>
#include <boost/bind.hpp>
#include <boost/bind/mem_fn.hpp>

// A value wrapper
template<typename T>
struct Value {
  Value(){}
  Value(const T& value, bool valid = true):m_value(value),m_valid(valid){}

  T getValue(){ return m_value; }
  bool getValid(){ return m_valid; }
  void setValue(const T& value){ m_value = value; }
  void setValid(const T& valid){ m_valid = valid; }

private:
  T m_value;
  bool m_valid;   
};

// Class that calculates the average piecewise
template<typename T>
struct Average {
private:
    T m_numPoints;
    T m_ChannelSum;

public:

    Average() : m_numPoints(0), m_ChannelSum(0.0){}

    void operator()(T value){
        m_numPoints++;
        m_ChannelSum+=value;
    }

    double getAverage(){ return m_ChannelSum/m_numPoints; }
    T getCount(){ return m_numPoints; }
    T getSum(){ return m_ChannelSum; }
};

// Run the average computation on several values
int main(int argc, char** argv){
  typedef int value_type;
  typedef Value<value_type> value_wrapper_type;
  typedef std::vector<value_wrapper_type> value_vector_type;
  value_vector_type values;
  values.push_back(value_wrapper_type(5));
  values.push_back(value_wrapper_type(7));
  values.push_back(value_wrapper_type(3));
  values.push_back(value_wrapper_type(1));
  values.push_back(value_wrapper_type(2));

  typedef Average<value_type> average_type;
  average_type avg;

#if 0
   // for loop version:
   for(value_vector_type::iterator it = values.begin(); it!=values.end(); it++){
     avg(it->getValue());  // I want to put this in a for_each loop
   }
#else
  //  bind version:
  std::for_each(values.begin(), values.end(), // iterate over all values
    boost::bind(
      boost::mem_fn(&average_type::operator()), // attach the averaging functor to the output of the getvalue call
      &avg, 
      boost::bind(
        boost::mem_fn(&value_wrapper_type::getValue), // bind the getValue call to each element in values
        _1
      )
    )
  );
#endif    
  std::cout << "Average: " << avg.getAverage() << " Count: " << avg.getCount() << " Sum: " << avg.getSum() << std::endl;
}

注意:我最初的问题是如何构建一个 for_each ,但我发现这个解决方案和一个全新的问题没有多大意义。

谢谢,非常感谢所有帮助!

4

5 回答 5

2

如果您使用的是 c++11,那么您可以尝试

for(auto& a: values)
    avg(a->getValue());

或者

std::for_each(a.begin(), a.end(), [](whatever_type& wt){
    avg(wt->getValue());
});

如果您不是,那么我认为该玩具与您将获得的一样好,尽管格式化不会受到伤害。

for(value_vector_type::iterator it = values.begin(); 
    it!=values.end(); 
    ++it)
{
    avg(it.getValue());  // I want to put this in a for_each loop
}

试图对函数对象等过于聪明通常会产生模糊代码的相反效果。

于 2012-02-29T22:45:30.007 回答
2

如果您没有 C++11 但 Boost 您可以尝试一个bind()表达式(它也可以与 C++2011 一起使用,因为bind()它是 C++2011 的一部分):

std::for_each(a.begin(), a.end(), bind(&avg<value_type>, bind(&Value<value_type>::getValue, _1)));
于 2012-02-29T22:49:50.427 回答
1

使它看起来更整洁的一种方法是使用Boost.Phoenix。你可以缩短到这个:

std::for_each(values.begin(), values.end(), lazy(avg)(arg1.getValue()));

下面是如何做到这一点。您需要做的第一件事是使avg函数对象变得惰性。最简单的方法是就地使用函数,定义如下:

template<class Function>
function<Function> lazy(Function x)
{
    return function<Function>(x);
}

接下来你需要为 getValue 编写一个函数对象,它可以是惰性的,如下所示:

struct get_value_impl
{
    // result_of protocol:
    template <typename Sig>
    struct result;

    template <typename This, typename T>
    struct result<This(Value<T>&)>
    {
        // The result will be T
        typedef typename T type;
    };

    template <typename V>
    typename result<get_value_impl(V &)>::type
    operator()(V & value) const
    {
        return value.getValue();
    }
};

第三,我们扩展了凤凰演员,使用我们的get_value_impl类,所以它会有一个getValue方法,像这样:

template <typename Expr>
struct value_actor
    : actor<Expr>
{
    typedef actor<Expr> base_type;
    typedef value_actor<Expr> that_type;

    value_actor( base_type const& base )
        : base_type( base ) {}

    typename expression::function<get_value_impl, that_type>::type const
    getValue() const
    {
        function<get_value_impl> const f = get_value_impl();
        return f(*this);
    }
};

最后,我们通过定义参数并将其传递给 for_each 算法将它们放在一起:

expression::terminal<phoenix::argument<1>, value_actor>  arg1;
std::for_each(values.begin(), values.end(), lazy(avg)(arg1.getValue()));
于 2012-03-02T05:36:50.743 回答
0

如果您可以使用 boost,但不能使用 C++11 功能,那么我会考虑使用BOOST_FOREACH 宏

是的,它是一个宏,但是随着宏的使用,它表现得很好

它读起来也很好,很难出错

BOOST_FOREACH(const Value& rValue, values)
{
    avg(rValue.getValue());
}

基于 for 循环的 C++11 范围将替换它

于 2012-03-03T21:41:38.743 回答
0

归功于 boost.users 邮件列表中的 Mathias Gaunard,他为我指出了这个解决方案:

  std::for_each(values.begin(), values.end(),
    boost::bind(boost::ref(avg), boost::bind(&value_wrapper_type::getValue, _1))
  );

包装avgwith是必需的,因为否则会用 的结果而不是本身填充boost::ref的副本。avggetValue()avg

这是完整的编译和测试解决方案:

#include <stdexcept>
#include <vector>
#include <algorithm>
#include <iostream>
#include <boost/bind.hpp>
#include <boost/bind/mem_fn.hpp>

// A value wrapper
template<typename T>
struct Value {
  Value(){}
  Value(const T& value, bool valid = true):m_value(value),m_valid(valid){}

  T getValue(){ return m_value; }
  bool getValid(){ return m_valid; }
  void setValue(const T& value){ m_value = value; }
  void setValid(const T& valid){ m_valid = valid; }

private:
  T m_value;
  bool m_valid;   
};

// Class that calculates the average piecewise
template<typename T>
struct Average {
private:
    T m_numPoints;
    T m_ChannelSum;

public:
  typedef void result_type;

    Average() : m_numPoints(0), m_ChannelSum(0.0){}

    result_type operator()(T value){
        m_numPoints++;
        m_ChannelSum+=value;
    }

    double getAverage(){ 
    if (m_ChannelSum==0) {
      throw std::logic_error("Cannot get average of zero values");
    }

    return m_ChannelSum/m_numPoints; 
  }
    T getCount(){ return m_numPoints; }
    T getSum(){ return m_ChannelSum; }
};

// Run the average computation on several values
int main(int argc, char** argv){
  typedef int value_type;
  typedef Value<value_type> value_wrapper_type;
  typedef std::vector<value_wrapper_type> value_vector_type;
  value_vector_type values;
  values.push_back(value_wrapper_type(5));
  values.push_back(value_wrapper_type(7));
  values.push_back(value_wrapper_type(3));
  values.push_back(value_wrapper_type(1)); 
  values.push_back(value_wrapper_type(2));

  typedef Average<value_type> average_type;
  average_type avg;

#if 0
  // for loop version:
  for(value_vector_type::iterator it = values.begin(); it!=values.end(); it++){
   avg(it->getValue());  // I want to put this in a for_each loop
  }
#else
  //  bind version:
  std::for_each(values.begin(), values.end(),
    boost::bind(boost::ref(avg), boost::bind(&value_wrapper_type::getValue, _1))
  );
#endif    
  std::cout << "Average: " << avg.getAverage() << " Count: " << avg.getCount() << " Sum: " << avg.getSum() << std::endl;
}
于 2012-03-01T23:51:17.197 回答