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不是标准的函数对象适配器。
答案 0 :(得分:0)
使用“纯”C ++ 03标准 - 你只能使用额外的bool数组:
将bind2nd(greater<int>(), x)
的所有结果存储到一个bool数组,第二个数组中的less
相同。 logical_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;
}