How to count the total numbers of a vector that are divisible by N in C++

1 Answer

0 votes
#include <iostream>
#include <algorithm>

using namespace std::placeholders;
 
bool DivisibleByN(int n , int d) {
    return n % d == 0;
}
 
int main() {
    std::vector<int> vec = { 5, 2, 7, 1, 9, 21, 3, 6, 14 };
    int n = 3;
     
    int count = std::count_if(vec.cbegin(), vec.cend(), std::bind(&DivisibleByN, _1, n));
    
    // 9, 21, 3, 6
    std::cout << "total = " << count; 
}
 
 
 
/*
run:
 
total = 4
 
*/

 



answered Aug 1, 2023 by avibootz
...