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

时间:2019-07-22 18:41:16

标签: c++ vector stdvector counting c++03

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

用于计数大于数字的元素的代码为:

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

对应功能:

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

问题是我仅在调用count_if函数之前才知道阈值(此处为8),因此我需要将阈值t作为参数传递。如何建立相同的?

3 个答案:

答案 0 :(得分:8)

最简单的方法是使用lambda expression。使用它,您可以在count_if的调用站点中构建函子(称为Closure Object),然后可以在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

答案 1 :(得分:2)

使函数具有阈值功能!

above

您只需使用阈值作为参数即可使用auto count = count_if(v.begin(), v.end(), above(8)); 获得计数:

var externalValidations = [
  function required(v, model = {}) {
     console.log(model)
     return v !== null || 'required field'
  },
  
  function requiredTwo(v, model = {}) {
     console.log(model)
     return v !== null || 'required field'
  },
]

externalValidations.forEach(item => {
  // --> Can I here somehow change the default value of a parameter for each function?! .. so it looks like this:
  // function requiredTwo(v, model = {value: 'value'}) {
  //   console.log(model)

  //   return v !== null || 'Campo obrigatório'
  // },
  console.log(item)
})

答案 2 :(得分:0)

NathanOliver said一样,我们需要“捕获”要在内部使用的阈值。一个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之前的版本中,我们必须手动创建这些轻量级的功能对象(有时称为 functors ,即使在技术上不正确)

C++03 Demo

现在事情变得简单多了:-)