C++ STL algorithm, count_if() program example

Compiler: Visual C++ Express Edition 2005

Compiled on Platform: Windows XP Pro SP2

Additional project setting: Set project to be compiled as C++

Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C++ Code (/TP)

Other info: none

To do: Using the C++ count_if() to return the number of elements in a range whose values match a specified condition in C++ programming

To show: How to use the C++ algorithm, count_if() to return the number of elements in a range whose values match a specified condition in C++ programming

// C++ STL algorithm, count_if()

#include<vector>

#include<algorithm>

#include<iostream>

usingnamespace std;

bool isgreat(int value)

{return (value > 8);}

int main(void)

{

// vector container

vector <int> vec;

// vector iterator

vector <int>::iterator Iter;

int result1;

// pushing data, constructing the vector

vec.push_back(13);

vec.push_back(21);

vec.push_back(9);

vec.push_back(31);

vec.push_back(8);

vec.push_back(10);

// printing the data

cout<<"vec vector data: ";

for(Iter = vec.begin(); Iter != vec.end(); Iter++)

cout<<*Iter<<" ";

cout<<endl;

// do some count_if() operation

cout<<"\nOperation: count_if(vec.begin(), vec.end(), isgreat)"<<endl;

result1 = count_if(vec.begin(), vec.end(), isgreat);

cout<<"The number of elements in vec vector greater than 8 is: "<<result1<<endl;

return 0;

}

Output examples:

vec vector data: 13 21 9 31 8 10

Operation: count_if(vec.begin(), vec.end(), isgreat)

The number of elements in vec vector greater than 8 is: 5

Press any key to continue . . .