Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

นับจำนวน 1 และ 0 ในอาร์เรย์ไบนารีด้วย STL ใน C++


ในบทช่วยสอนนี้ เราจะพูดถึงโปรแกรมนับจำนวน 1 และ 0 ในอาร์เรย์ไบนารีโดยใช้ STL ใน C++

ให้อาร์เรย์หนึ่ง เราต้องนับจำนวน 0 และ 1 ที่ปรากฏในอาร์เรย์

ตัวอย่างโค้ด

#include <bits/stdc++.h> 
using namespace std; 

// ตรวจสอบว่าองค์ประกอบเป็น 1 หรือไม่
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