2012-04-23 26 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來結合兩個條件

我曾嘗試下面的代碼,它不工作:

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不是一個標準函數對象適配器。

+0

那麼,你可以嘗試改變'boost :: bind'到'std :: bind'。 – 2012-04-23 16:01:09

+0

std ::將一個新的函數綁定到C++ 11上?如果可能的話,我想看看如何使用'std :: bind1st'或'std :: bind2nd'來實現。 – q0987 2012-04-23 16:04:58

+1

在C++ 03中,使用'std :: bind1st','std :: bind2nd'和'std :: compose2'。有關示例,請參見[這裏](http://www.sgi.com/tech/stl/logical_and.html)。 – 2012-04-23 16:11:10

回答

0

用「純」 C++ 03的std - 你只能使用額外的布爾數組做到這一點: 存儲所有結果從bind2nd(greater<int>(), x)一個布爾數組,在第二陣列相同的lesslogical_and結果到第三個數組。對於動態大小 - 使用std :: vector而不是簡單的原始數組。或者從http://www.sgi.com/tech/stl/stl_function.h複製(竊取)SGI STL compose2<>的實施。

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