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

#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(), [&](int& d){d = dist(engine);});
	int numNegative = std::count_if(v.begin(), v.end(), [&](const int d){return d<0;});
	int numNonNegative = std::count_if(v.begin(), v.end(), [&](const int d){return d>=0;});
	int numZero = std::count_if(v.begin(), v.end(), [&](const int d){return d==0;});
	int numNonZero = std::count_if(v.begin(), v.end(), [&](const int d){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;
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s