我想计算 c++ 向量中大于数字的元素数。阈值将从用户那里获取输入。
计数大于数字的元素的代码如下:
ctr=count_if(v.begin(),v.end(), greater1);
对应功能:
bool greater1(int value)
{
return value >= 8;
}
问题是我只会在count_if
函数调用之前知道阈值(此处为 8(,所以我需要将阈值t
作为参数传递。如何建立相同?
> 注意仅适用于 c++11 标准
最简单的方法是使用 lambda 表达式。 使用它,您可以在 count_if
的调用站点中构建一个函子(称为闭包对象(,并且您可以在 lambda 的主体中使用您当时所知道的函子。 那会给你留下类似的东西
auto minimum_value = /* something that gets the minimum value you want to use for the comparison */
auto count = std::count_if(v.begin(), v.end(),[&](auto const& val){ return val >= minimum_value; });
// ^ use this to capture a reference of minimum_value
做一个给你阈值函数的函数!
auto above(int threshold) {
// This captures a copy of threshold
return [=](int value) {
return value >= threshold;
};
};
然后,您可以使用 above
获取计数,只需将阈值作为参数传递即可:
auto count = count_if(v.begin(), v.end(), above(8));
就像NathanOliver所说,我们需要"捕获"内部使用的阈值。lambda 可以做到这一点,但如何实现呢?
当你写一个像 lambda 一样
int threshold = 8;
std::count_if(/*...*/, [threshold](int next_val){return next_val >= threshold;});
在 C++11 及更高版本中,编译器使用此 lambda 语法生成一个轻量级类,该类公开函数调用运算符,如下所示:
struct my_greater_equal
{
explicit my_greater_equal(int _threshold) : threshold(_threshold){}
bool operator()(int next_val) const
{
return next_val >= threshold;
}
int threshold;
};
(这主要只是像lambda的样子(
然后创建一个实例,并以count_if
假设的形式使用:
std::count_if(my_collection.cbegin(), my_collection.cend(), my_greater_equal{8});
在内部,std::count_if
为集合中的每个元素调用my_greater_equal::operator()
。
在C++11之前,我们必须手动创建这些轻量级函数对象(有时称为函子,即使这在技术上不正确(
C++03 演示
现在事情容易多了:-(