I am Charmie

メモとログ

C++: count some elements of std::vector

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&amp; d){std::cout &lt;&lt; d &lt;&lt; &quot;, &quot;;}); std::cout &lt;&lt; std::endl;
std::cout &lt;&lt; &quot;numNegative = &quot; &lt;&lt; numNegative &lt;&lt; std::endl;
std::cout &lt;&lt; &quot;numNonNegative = &quot; &lt;&lt; numNonNegative &lt;&lt; std::endl;
std::cout &lt;&lt; &quot;numZero = &quot; &lt;&lt; numZero &lt;&lt; std::endl;
std::cout &lt;&lt; &quot;numNonZero = &quot; &lt;&lt; numNonZero &lt;&lt; std::endl;

return 0;

} [/code]