C++ STL algorithm, count_if(), begin() and end() 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_if() to count items in a range that satisfy a predicate, begin() to return an iterator that points to the first element in a sequence and end() to return an iterator that points one past the end of a sequence in C++ programming

To show: How to use the C++ algorithm, count_if() to count items in a range that satisfy a predicate, begin() to return an iterator that points to the first element in a sequence and end() to return an iterator that points one past the end of a sequence in C++ programming

 

// C++ STL algorithm, count_if(), begin() and end()

#include <iostream>

#include <algorithm>

#include <functional>

#include <string>

#include <vector>

using namespace std;

 

// return true if string str starts with letter 'C'

int MatchFirstChar(const string& str)

{

string s("C");

return s == str.substr(0, 1);

}

 

int main(void)

{

// define a template class vector of strings, simplified the name using typedef

typedef vector<string> StringVector;

// define an iterator for template class vector of strings, simplified the name using typedef

typedef StringVector::iterator StringVectorIt;

 

// vector containing names

StringVector NamesVect(110);

StringVectorIt start, end, it;

 

// stores count of elements that match value.

ptrdiff_t result = 0;

 

// initialize vector NamesVect

NamesVect[0] = "Learn";

NamesVect[1] = "C";

NamesVect[2] = "and";

NamesVect[3] = "C++";

NamesVect[4] = "also";

NamesVect[5] = "Visual";

NamesVect[6] = "C++";

NamesVect[7] = "and";

NamesVect[8] = "C++";

NamesVect[9] = ".Net";

 

// location of first element of NamesVect

start = NamesVect.begin();

// one past the location last element of NamesVect

end = NamesVect.end();

// print content of NamesVect

cout<<"NamesVect: ";

for(it = start; it != end; it++)

cout<<*it<<" ";

cout<<endl;

// count the number of elements in the range [first, last +1) that start with letter 'C'

result = count_if(start, end, MatchFirstChar);

// print the count of elements that start with letter 'S'

cout<<"Number of elements that start with letter \"C\" = "<<result<<endl;

return 0;

}

 

Output examples:

 

NamesVect: Learn C and C++ also Visual C++ and C++ .Net

Number of elements that start with letter "C" = 4

Press any key to continue . . .

 

 

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