使用C++ STL查找数组中奇数和偶数元素


给定一个数组,任务是使用C++标准模板库查找数组中奇数和偶数元素的个数。

为了解决这个问题,我们使用C++标准模板库中的`count_if()`函数。什么是`count_if()`函数?

语法

count_if(LowerBound, UpperBound, function)

**描述** − 此函数返回数组中满足给定条件的元素个数。它接受三个参数。

  • **下界** − 它指向数组或任何其他序列的第一个元素。
  • **上界** − 它指向数组或任何其他序列的最后一个元素。
  • **函数** − 根据指定的条件返回布尔值。

示例

Input-: array[] = {2, 4, 1, 5, 8, 9}
Output-: Odd elements are: 1, 5 and 9. So, total number of odds is 3
Even elements are: 2, 4 and 8
Input-: array[] = {1, 2, 3, 4, 5, 10}
Output-: Odd elements are: 1, 3 and 5. So, total number of odds is 3
Even elements are: 2, 4 and 10. So, total number of evens is 3

**下面程序中使用的方案如下** −

  • 将整数值输入到整型数组中
  • 创建布尔函数以检查数组元素是否为奇数。如果选择的元素为奇数,则其余元素将为偶数。
  • 调用`count_if()`函数,该函数将第一个元素、最后一个元素和函数作为参数。

示例

 在线演示

#include <bits/stdc++.h>
using namespace std;
// Function to check if the element is odd or even
bool check(int i) {
   if (i % 2 != 0)
      return true;
   else
      return false;
}
int main() {
   int arr[] = { 2, 10, 1, 3, 7, 4, 9 };
   int size = sizeof(arr) / sizeof(arr[0]);
   int temp = count_if(arr, arr + size, check);
   cout << "Odds are : " <<temp << endl;
   cout << "Evens are : " << (size - temp) << endl;
   return 0;
}

输出

如果我们运行上述代码,它将生成以下输出:

Odds are: 4
Evens are: 3

更新于:2020年1月20日

227 次查看

开启你的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.