Home > C++, VC++ > Some interesting uses of count_if stl algorithm function!

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. 🙂

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 );

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

int AlnumCount = (int)std::count_if( &SomeString[0], &SomeString[strlen(SomeString)], isalnum );

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

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 );

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.

Advertisements
  1. October 10, 2008 at 11:28 am

    🙂

  2. cppkid
    October 10, 2008 at 10:14 am

    Nice explanation….Great!!!

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: