Some interesting uses of count_if stl algorithm function!

STL algorithm count_if function is a fun function with some serious usages associated with it. Main benefit of using count_if is that we can use normal character arrays/pointers along with normal CRT functions like isupper, islower etc.

Using count_if to get count of lower/upper case characters in a string

Just one function call and we get count of lower/upper case characters. No loops written by us. 🙂

[sourcecode language=’cpp’]char SomeString[]    = “Nibu loves Jesus Christ, these Tips are dedicated to Him. Read John 3:16 for the reason.”;
const size_t Len = strlen(SomeString)-1;
int LowerCaseCount = (int)std::count_if( &SomeString[0], &SomeString[Len], islower );
int UpperCaseCount = (int)std::count_if( &SomeString[0], &SomeString[Len], isupper );[/sourcecode]

Using count_if to get count of alpha numeric characters in a string

[sourcecode language=’cpp’]int AlnumCount = (int)std::count_if( &SomeString[0], &SomeString[strlen(SomeString)], isalnum );[/sourcecode]

Using count_if to get count of odd/even numbers in an integer array

[sourcecode language=’cpp’]
bool IsOdd( const int Num ){ return ( Num % 2 != 0 ); }
bool IsEven( const int Num ){ return ( Num % 2 == 0 ); }

int Numbers[100] = { 0 };
// Fill with random numbers
std::generate( &Numbers[0], &Numbers[_countof(Numbers)], rand );
int OddCount  = (int)std::count_if( &Numbers[0], &Numbers[_countof(Numbers)], IsOdd );
int EvenCount = (int)std::count_if( &Numbers[0], &Numbers[_countof(Numbers)], IsEven );[/sourcecode]

The secret is that, compiler finds out type of template arguments passed in and also makes sure that function arguments are given appropriate types, during compilation compiler knows what are the types passed to a function hence this is possible.

Last argument to count_if is a functor. A functor is a function object with an overridden function call operator. Real cool part is that even CRT functions are treated as functors. 🙂 Isn’t this simple.

There are plenty more uses of std::count_if and I hope this post acts as a starter for you explore the stl library.

2 thoughts on “Some interesting uses of count_if stl algorithm function!

Appreciate your comments...