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 实现相同的逻辑。我怎样才能做到这一点?

我已经尝试了以下代码,但它不起作用:

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 不是标准的函数对象适配器。

4

1 回答 1

0

使用“纯”C++03 std - 您只能通过使用额外的 bool 数组来做到这一点:将所有结果存储bind2nd(greater<int>(), x)到一个 bool 数组中,与less第二个数组相同。结果logical_and到第三个数组。对于动态大小 - 使用 std::vector 而不是简单的原始数组。compose2<>或者只是从http://www.sgi.com/tech/stl/stl_function.h复制(窃取)SGI STL 的实现。

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;
}
于 2012-09-26T15:54:11.100 回答