count_if counts the number of elements that satisfies the specified condition.
The result is like the following: 79, 55, 57, 44, 0, 14, -5, 52, 86, 95, -7, 100, 5, -5, 95, 19, 63, 59, 40, 51, numNegative = 3 numNonNegative = 17 numZero = 1 numNonZero = 19
[code lang="cpp"]
include <iostream>
include <vector>
include <random>
include <algorithm>
int main(int argc, char* argv[]) { std::random_device rd; std::mt19937 engine(rd()); std::uniform_int_distribution<int> dist(-10, 100); std::vector<int> v(20); std::for_each(v.begin(), v.end(), &{d = dist(engine);}); int numNegative = std::count_if(v.begin(), v.end(), &{return d<0;}); int numNonNegative = std::count_if(v.begin(), v.end(), &{return d>=0;}); int numZero = std::count_if(v.begin(), v.end(), &{return d==0;}); int numNonZero = std::count_if(v.begin(), v.end(), &{return d!=0;});
std::for_each(v.begin(), v.end(), [](const int& d){std::cout << d << ", ";}); std::cout << std::endl;
std::cout << "numNegative = " << numNegative << std::endl;
std::cout << "numNonNegative = " << numNonNegative << std::endl;
std::cout << "numZero = " << numZero << std::endl;
std::cout << "numNonZero = " << numNonZero << std::endl;
return 0;
} [/code]