温馨提示×

如何结合C++模板使用count_if

c++
小樊
82
2024-08-23 18:01:37
栏目: 编程语言

可以通过在C++中使用模板和lambda表达式来结合使用count_if函数。以下是一个简单的示例:

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

template <typename T>
int countOddNumbers(const std::vector<T>& vec) {
    return std::count_if(vec.begin(), vec.end(), [](T n) { return n % 2 != 0; });
}

int main() {
    std::vector<int> numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

    int oddCount = countOddNumbers(numbers);
    std::cout << "There are " << oddCount << " odd numbers in the vector." << std::endl;

    return 0;
}

在这个示例中,我们定义了一个模板函数countOddNumbers,该函数接受一个向量并使用lambda表达式来检查其中的每个元素是否为奇数。然后,我们在main函数中调用这个模板函数,并打印出向量中奇数的数量。通过使用模板和lambda表达式,我们可以更灵活地处理不同类型的元素。

0