“std::count_if”的二进制谓词不起作用

Binary predicate for `std::count_if` is not working

本文关键字:二进制 谓词 不起作用 if std count      更新时间:2023-10-16

我目前正在尝试使用 lambda 函数来std::count_if数组中两个连续元素的总和等于一个数字。下面给出了一个示例代码。

#include <iostream>
#include <vector>
#include <algorithm>
int main()
{
    const int Number = 3;
    std::vector<int> vec = {1,1,2,4,5,6};    
    auto count = std::count_if( vec.begin(), vec.end(),
    [&](int A, int B) -> bool
    {   return A+B == Number;   });
    std::cout << count << 'n';
}

输出应该是1的,因为我们有一个可能的情况(1 + 2(。

但是,我无法成功。谁能告诉我我错过了什么?这是错误消息:

|234|error: no match for call to '(main()::<lambda(int, int)>) (int&)'|

问题是 std::count_if 使用一元谓词。编译器告诉你:"你给了我一个带有 2 个参数的 lambda,我期望有一个参数的 lambda"。

我相信你正在寻找的是std::adjacent_find。它比较容器的每个相邻元素(可能使用二进制谓词(。

另一种可能的选择是使用 std::inner_product .首先,我会写一个小的辅助函数:

#include <numeric>
#include <functional>
#include <iterator>
template <typename ForwardIterator, typename BinaryPredicate>
auto count_pairs_if(ForwardIterator first, ForwardIterator last, 
                    BinaryPredicate pred)
{
    const auto n = std::distance(first, last);
    if (n < 2) return std::size_t {0};
    return std::inner_product(first, std::next(first, n - 1), std::next(first),
                              std::size_t {0}, std::plus<> {}, pred);
}
template <typename Range, typename BinaryPredicate>
auto count_pairs_if(const Range& values, BinaryPredicate pred)
{
    return count_pairs_if(std::cbegin(values), std::cend(values), pred);
}

然后你可以像这样使用它:

auto count = count_pairs_if(vec, [=] (auto lhs, auto rhs) { return lhs + rhs == Number; });

这是一个演示。

正如@Yksisarvinen所解释的,std::count_if是为一元谓词设计的。因此编译器不能接受lambda,我通过了。

一段时间后,我找到了这个问题的另一种解决方案。如果我提供一个模板化函数,它需要

  1. 容器的迭代器(即开始和结束((我需要在其上进行相邻元素检查(,以及
  2. 二进制谓词,将用于检查相邻关系

这可能是一个更自然的解决方案,就像任何其他标准算法一样。(在线观看现场演示(

template <typename Iterator, typename BinaryPred = std::equal_to<>>
constexpr std::size_t count_adjacent_if(
   Iterator beginIter,
   const Iterator endIter,
   const BinaryPred pred = {})
{
   if (beginIter == endIter) return 0; // nothing to do!
   std::size_t count{};
   for (Iterator nextIter{ beginIter }; ++nextIter != endIter; beginIter = nextIter)
      if (pred(*beginIter, *nextIter))
         ++count;
   return count;
}

并且可以像这样称为:

const auto count = ::count_adjacent_if(
   vec.cbegin(), vec.cend(), [number](const int lhs, const int rhs) { return lhs + rhs == number; }
);

或者像@bipil评论中提到的,让谓词记住前面的元素。不太推荐,因为它是非通用解决方案并且需要非空容器。(在线观看现场演示(

int lhs = vec[0];
const auto count = std::count_if(vec.cbegin() + 1, vec.cend(),
   [&](const int rhs) {
   const bool condition = (lhs + rhs == number); // check for the condition
   lhs = rhs; // change the lhs = rhs (i.e. current element = next element)
   return condition; // return the condition
});