Demonstrate count and count_if.
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
bool even(int x)
{
return !(x%2);
}
int main()
{
vector<int> vectorObject;
int i;
for(i = 0; i <20; i++) {
if(i%2) vectorObject.push_back(1);
else vectorObject.push_back(2);
}
cout << "Sequence: ";
for(i = 0; i <vectorObject.size(); i++)
cout << vectorObject[ i ] << " ";
cout << endl;
int n;
n = count(vectorObject.begin(), vectorObject.end(), 1);
cout << n << " elements are 1\n";
n = count_if(vectorObject.begin(), vectorObject.end(), even);
cout << n << " elements are even.\n";
return 0;
}
Related examples in the same category