2012-02-10 8 views
0

型Tのリストと述語(指定された関数へのポインタ)を指定して、リスト内のいくつの要素が真を返すかを数える関数を作成しました。N進述語評価の関数(count_if)

これはアトミック述語(isEven、isOdd、is_less_than_42)で動作しますが、N進述語で使用するにはどうすればよいですか? N-ary述語が必要とするN-1引数のオプションリストを渡す方法はありますか?

template<typename T, class Pred> 
int evaluate(listofelements<T> &sm, Pred pred){ 
    typename listofelements<T>:: iterator begin, end; 
    int count=0; 
    begin=sm.begin(); 
    end=sm.end(); 
    while(begin!=end){ 
     if(pred(*(begin->data))) count++; 
     begin++; 
    } 
    return count; 
} 

答えて

1

あなたは単項関数オブジェクトにN-aryの機能を変換するためにstd::bindを使用することができます。

using std::placeholders::_1; 

evaluate(sm, std::bind(some_function, _1, other, arguments)); 

std::bindはC++ 11であるが、古いコンパイラでは、あなたがstd::tr1::bind使い、最後にまだBoost.Bindがある可能性がどこTR1が含まれている可能性があります。

それとも、機能を自分でオブジェクトを作ることができます:

struct SomeFunctor 
{ 
    SecondType arg2; 
    ThirdType arg3; 
    SomeFunctor(cosnt SecondType& arg2, const ThirdType& arg3) 
     : arg2(arg2), arg3(arg3) 
    {} 

    ResultType operator()(const FirstType& arg1) const 
    { 
     return some_function(arg1, arg2, arg3); 
    } 
}; 

evaluate(sm, SomeFunctor(other, arguments)); 
//   ^construct SomeFunctor with arg2=other, arg3=arguments 
+0

あなたはコードはあなたが作品を掲載方法を説明してもらえますか?私はちょっと混乱しています、特にdoubleを返すoperator()についてです。 – Vektor88

+0

@vektor88: 'operator()'の構造体は[function object(別名Functor)です](http://stackoverflow.com/questions/ 356950/c-functors-and-their-uses) – kennytm

+0

私は知っていますが、私はこのコードが何をし、どのように使用するべきかを知りません。 Arg0は私の*(begin-> data)のようです – Vektor88