使用 C++ 中的 STL 计算二进制数组中 1 和 0 的数量
在本文中,我们将讨论一个程序,使用 C++ 中的 STL 来计算二进制数组中 1 和 0 的数量。
为此,我们将提供一个数组。我们的任务是计算数组中存在的 0 和 1 的数量。
示例
#include <bits/stdc++.h>
using namespace std;
// checking if element is 1 or not
bool isOne(int i){
if (i == 1)
return true;
else
return false;
}
int main(){
int a[] = { 1, 0, 0, 1, 0, 0, 1 };
int n = sizeof(a) / sizeof(a[0]);
int count_of_one = count_if(a, a + n, isOne);
cout << "1's: " << count_of_one << endl;
cout << "0's: " << (n - count_of_one) << endl;
return 0;
}输出
1's: 3 0's: 4
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP