2012-04-23 4 views
1
int nums[] = {7, 6, 12, 9, 29, 1, 67, 3, 3, 8, 9, 77}; 
    std::vector<int> vecInts(&nums[0], &nums[0] + sizeof(nums)/sizeof(nums[0])); 

    int countBoost = 0; 

    // (i > 5 && i <=10) 
    countBoost = std::count_if(vecInts.begin(), vecInts.end(), 
         boost::bind(std::logical_and<bool>(), 
            boost::bind(std::greater<int>(), _1, 5), 
             boost::bind(std::less_equal<int>(), _1, 10)) 
         ); 

ここでは、純粋なSTLと同じ論理を実装する必要があります。どうやってやるの?std :: logical_andを使用して2つの条件を結合する

私は、次のコードを試してみました、それが動作しません:

int countSTL = std::count_if(vecInts.begin(), vecInts.end(), 
          std::logical_and<bool>(std::bind2nd(std::greater<int>(), 5), std::bind2nd(std::less_equal<int>(), 10))        
         ); 

//更新//

In Effective STL Item 43, Meyers indicates as follows: 

vector<int>::iterator i = find_if(v.begin(), v.end(), 
      compose2(logical_and<bool>(), bind2nd(greater<int>(), x), 
             bind2nd(less<int>(), y))); 

しかしcompose2標準ではありませんありがとう関数オブジェクトアダプタ。 「純粋な」C++ 03のstdで

+0

さて、 'boost :: bind'を' std :: bind'に変更してみることができます。 –

+0

std :: bindは新しい関数をC++ 11にバインドしていますか?可能であれば、 'std :: bind1st'や' std :: bind2nd'を実装する方法を見たいと思います。 – q0987

+1

C++ 03では、 'std :: bind1st'、' std :: bind2nd'と 'std :: compose2'を使います。例については、[here](http://www.sgi.com/tech/stl/logical_and.html)を参照してください。 –

答えて

0

- あなただけの追加のブール配列を使用してこれを行うことができます。 ストアbind2nd(greater<int>(), x)からのすべての結果二番目の配列でlessに同じ1つのブール配列へ。 logical_andは3番目の配列になります。動的なサイズの場合は、単純な生の配列の代わりにstd :: vectorを使用します。 SGI STL compose2<>の実装をhttp://www.sgi.com/tech/stl/stl_function.hからコピー(盗み)してください。

int main() { 
    int nums[] = {7, 6, 12, 9, 29, 1, 67, 3, 3, 8, 9, 77}; 
    const size_t NUMS_SIZE = sizeof(nums)/sizeof(*nums); 
    bool nums_greater[NUMS_SIZE]; 
    bool nums_less[NUMS_SIZE]; 
    bool nums_greater_and_less[NUMS_SIZE]; 

    int x = 3; 
    int y = 20; 
    transform(nums, nums + NUMS_SIZE, nums_greater, bind2nd(greater<int>(), x)); 
    transform(nums, nums + NUMS_SIZE, nums_less, bind2nd(less<int>(), y)); 
    transform (nums_greater, nums_greater+NUMS_SIZE, nums_less, nums_greater_and_less, 
       logical_and<bool>()); 

    int countBoost = 0; 

    countBoost = count(nums_greater_and_less, nums_greater_and_less + NUMS_SIZE, true); 

    cout << countBoost << endl; 
} 
関連する問題