C++ STL algorithm, count() program example

 

Compiler: Visual C++ Express Edition 2005

Compiled on Platform: Windows XP Pro SP2

Header file: Standard

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() to returns the number of elements in a range whose values match a specified value in C++ programming

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

 

// C++ STL algorithm, count()

#include <vector>

#include <algorithm>

#include <iostream>

using namespace std;

 

int main(void)

{

// vector container

vector <int> vec;

// vector iterator

vector <int>::iterator Iter;

int result;

 

// push data, constructing the vector

vec.push_back(12);

vec.push_back(22);

vec.push_back(12);

vec.push_back(31);

vec.push_back(12);

vec.push_back(33);

 

// print the data

cout<<"vec vector data: ";

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

cout<<*Iter<<" ";

cout<<endl;

 

// do some count() operation

cout<<"\nOperation: count(vec.begin(), vec.end(), 12)"<<endl;

result = count(vec.begin(), vec.end(), 12);

cout<<"The number of 12s in vec vector is: "<<result<<endl;

return 0;

}

 

Output examples:

 

vec vector data: 12 22 12 31 12 33

Operation: count(vec.begin(), vec.end(), 12)

The number of 12s in vec vector is: 3

Press any key to continue . . .

 

 

C and C++ Programming Resources | C & C++ Code Example Index