温馨提示×

count_if在C++中的错误用法

c++
小樊
83
2024-08-23 17:57:31
栏目: 编程语言

count_if函数在C++中用于统计容器中满足特定条件的元素个数,下面是一个错误的例子:

#include <iostream>
#include <vector>
#include <algorithm>

int main() {
    std::vector<int> vec = {1, 2, 3, 4, 5};
    
    int count = std::count_if(vec.begin(), vec.end(), vec.size() > 3);
    
    std::cout << "Count: " << count << std::endl;
    
    return 0;
}

上面的代码中,错误地将vec.size() > 3作为谓词传递给count_if函数,这是错误的用法。正确的做法是使用lambda表达式或者函数对象来定义一个合法的谓词。例如:

int count = std::count_if(vec.begin(), vec.end(), [](int i) { return i > 3; });

或者:

struct IsGreaterThanThree {
    bool operator()(int i) const {
        return i > 3;
    }
};

int count = std::count_if(vec.begin(), vec.end(), IsGreaterThanThree());

这样才能正确地统计容器中满足条件的元素个数。

0