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を持っていないがBoostを使用している場合は、bind()式を試すことができます(C++2011bind()の一部である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 に答える
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 に答える
1

見栄えを良くする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_impl3番目に、クラスを使用してフェニックスアクターを拡張します。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.usersメーリングリストのMathiasGaunardにクレジットがあります。

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

でラップavgするboost::ref必要があります。そうしないと、のコピーがそれ自体ではなくavg、の結果で埋められるためです。getValue()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 に答える
0

ブーストは使用できるがC++11機能は使用できない場合は、BOOST_FOREACHマクロの使用を検討します

はい、それはマクロですが、マクロが進むにつれて、それはうまく動作します

それはまた非常によく読み、間違いを犯しにくいです

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

C++11の範囲ベースのforループが置き換えられます

于 2012-03-03T21:41:38.743 に答える