繁体   English   中英

计算大于向量中数字的元素

[英]Counting elements greater than a number in vector

我想计算c ++向量中大于数字的元素数。 阈值将从用户输入。

计算大于数字的元素的代码如下:

ctr=count_if(v.begin(),v.end(), greater1);

相应的功能:

bool greater1(int value)
{
   return value >= 8;
}

问题是我只知道在count_if函数调用之前的阈值(这里是8),所以我需要将阈值t作为参数传递。 如何建立相同?

NB仅适用于c ++ 11标准

最简单的方法是使用lambda表达式 使用它可以在count_if的调用站点中构建一个仿函数(称为Closure对象),然后您可以在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 as-if:

std::count_if(my_collection.cbegin(), my_collection.cend(), my_greater_equal{8});

在内部, std::count_if为集合中的每个元素调用my_greater_equal::operator()

Pre-C ++ 11我们必须手动创建这些轻量级函数对象 (有时称为仿函数,即使这在技术上并不正确)

C ++ 03演示

事情现在变得容易多了:-)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM