Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C++

Tìm phần tử chia hết cho N trong mảng dùng STL C++

Cho mảng, đếm số phần tử chia hết cho N sử dụng STL count_if() trong C++.

Hàm count_if()

Cú pháp: count_if(LowerBound, UpperBound, function)

Trả về số phần tử thỏa điều kiện. Tham số: iterator đầu, iterator cuối, hàm predicate.

Ví dụ

Input: array[] = {2, 4, 1, 5, 8, 9}, N = 4
Output: Elements divisible by 4: 2 (4 và 8)
Input: array[] = {1, 2, 3, 4, 5, 10}, N = 2
Output: Elements divisible by 2: 3 (2, 4, 10)

Chương trình mẫu

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

int n; // biến toàn cục để predicate truy cập

bool check(int i) {
    return (i % n == 0);
}

int main() {
    int arr[] = {2, 4, 1, 5, 8, 9};
    n = 4;
    int size = sizeof(arr) / sizeof(arr[0]);
    int count = count_if(arr, arr + size, check);
    cout << "Elements divisible by " << n << ": " << count;
    return 0;
}

Kết quả

Elements divisible by 4: 2

Lưu ý: Biến n khai báo toàn cục để hàm check truy cập. Có thể dùng lambda (C++11) để gọn hơn: count_if(arr, arr+size, [n](int x){ return x%n==0; }).