gpt4 book ai didi

c++ - 使用 std::logical_and 组合两个条件

转载 作者:太空宇宙 更新时间:2023-11-04 14:17:07 26 4
gpt4 key购买 nike

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

But compose2 is NOT a standard function object adapter.

最佳答案

使用“纯”C++03 标准 - 你只能通过使用额外的 bool 数组来做到这一点:存储来自 bind2nd(greater<int>(), x) 的所有结果到一个 bool 数组,与 less 相同在第二个数组中。 logical_and结果到第三个数组。对于动态大小——使用 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;
}

关于c++ - 使用 std::logical_and 组合两个条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10284007/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com