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

   2024-10-01 6170
核心提示:可以通过在C++中使用模板和lambda表达式来结合使用count_if函数。以下是一个简单的示例:#include iostream#include algorithm#i

可以通过在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表达式,我们可以更灵活地处理不同类型的元素。

 
举报打赏
 
更多>同类物流大全
推荐图文
推荐物流大全
点击排行

网站首页  |  关于我们  |  联系方式网站留言    |  赣ICP备2021007278号