Page 1 of 1

## C++ STL UNARY PREDICATE FUNCTIONS TUTORIAL C++ STL UNARY PREDICATE FUNCTIONS TUTORIAL Rate Topic:     //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'https://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=119818&amp;s=ca46d3da89f16ffc3de26d1d03dc1dff&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

### #1 Elcric Reputation: 102
• Posts: 453
• Joined: 02-May 09

Posted 12 August 2009 - 06:54 AM

C++ STL UNARY PREDICATE FUNCTIONS TUTORIAL

WHAT YOU WILL LEARN IN THIS TUTORIAL:

1. You will learn how to write STL unary predicates.
2. You will learn how to use the STL unary predicate functions with arrays.
3. You will learn how to use the STL unary predicate functions with lists.
4. You will learn how to use the STL unary predicate functions with vectors.

 I. INTRODUCTION

Hello; nice to meet you! Welcome to the C++ STL Unary Predicate Function Tutorial.

 II. PREDICATE FUNCTIONS

Predicate functions test the truth or falsity of conditions; for example, an isEmpty function or an isFull function. A binary predicate function takes two arguments, performs a comparison using those two arguments and returns a bool value indicating the result. A unary predicate function takes a single value argument, performs a comparison using that argument and returns a bool value indicating that result.

A. UNARY PREDICATE FUNCTIONS

Examples of the unary predicate functions are: replace_if, remove_if, partition, stable_partition, replace_copy_if, remove_copy_if, count_if, and find_if.

In the STL, instead of seeing unary predicate function you will normally just see the word predicate.

For discussion purposes, lets take a look at the STL count_if() function.
The count_if() function has three parameters. The first parameter is the starting point. The second parameter is the ending point. The third parameter is the unary predicate which returns the condition you want for inclusion in the count returned by the count_if() function.

count_if() returns the total of the number of elements that match a unary predicate condition between the starting point and the ending point in a series of elements.

1. ARRAY EXAMPLE

The syntax for instantiating an array object is as follows:
type arrayName [arrayElements];

a. A one-dimensional array name by itself without the elements enclosed by the square brackets is automatically converted to a pointer to the address of the first element of the array. Therefore, the array name A, in the attached array example program, is used for the first parameter.

b. The amount of memory required to store each element of an array is determined by its type. And, all the elements of the array are stored in a contiguous block of memory. Therefore, the sizeof operator is very useful when working with an array. In the const int N = (sizeof(A) / sizeof(A)); statement of the attached array example program; sizeof() divides the number of bytes occupied by the whole A array by the number of bytes occupied by the first element of the A array. Because each element in the array occupies the same amount of memory, the result is the number of elements in the A array. After being computed, the number of elements in the A array is assigned to the variable N. Using pointer arithmetic, A + N is used for the second parameter.

c. The third parameter is the unary predicate which returns the condition you want for inclusion in the count returned by the count_if() function. The attached example program unary predicate function name is isMoreThan30.

Attached is the array example program:

```//**************************************
//C++ STL PREDICATE FUNCTIONS TUTORIAL
//Array Example:
//**************************************
#ifndef CALC_ERROR_H
#define CALC_ERROR_H
#include <algorithm>
#include <cstdlib>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <vector>
using namespace std;
#endif  //CALC_ERROR_H

void ClearScreen();				//Clears the screen.
void Pause();					  //Waits for user response.
bool evenlyDivisibleByTwo(int i);  //Returns true if number is an even number.

//************************************
//Clear Screen.
//************************************
void ClearScreen()
{
system( "CLS" );
cout << endl << endl << endl;
}

//************************************
//Pause.
//************************************
void Pause()
{
cout << endl << endl << endl;
cout << "  ";
system( "PAUSE" );
}

//************************************
//Unary Predicate Function:
//Returns true if number is more than
//30.
//************************************
bool isMoreThan30( int value )
{
return value >30;
}

//************************************
// MAIN() FUNCTION.
//************************************
int main(int argc, char* argv[])
{
ClearScreen();
int A[] = { 9, 12, 32, 18, 4, 96, 5, 42, 33, 10 };
const int N = (sizeof(A) / sizeof(A));
cout << endl << endl;

cout << "  The " << count_if(A, (A + N), isMoreThan30);

cout << " numbers more than 30 are: ";
for( int i = 0; i < N; i++ )
{
if (isMoreThan30( A[ i ] ))
{
cout << A[ i ] << " ";
}
}
Pause();
return EXIT_SUCCESS;
}

```

2. LIST EXAMPLE:

The syntax for instantiating a list object is as follows:
list <type> objectName;

list is a C++ keyword. The angle brackets contain the word type <type> which is a placeholder for the type of the list you are instantiating. objectName is the name of the list object you are instantiating.
When working with a list the count_if() functions three parameters are as follows:

a. objectName.begin() sets the list element starting point.
begin() is a function that automatically moves the pointer to the first element of the list.

b. objectName.end() sets the list element ending point.
end() is a function that automatically works with the begin() function to establish a range of list elements which will be tested for the condition of the unary predicate. In this case the range is from the first element of the list to the last element of the list.

c. Unary Predicate

The unary predicate is established by the programmer by writing a Boolean function which returns the appropriate condition for the count_if() function. The attached list example program unary predicate function name is isDivisibleByThree.

Attached is the list example program:

```//**************************************
//C++ STL PREDICATE FUNCTIONS TUTORIAL
//List Example:
//**************************************
#ifndef CALC_ERROR_H
#define CALC_ERROR_H
#include <algorithm>
#include <cstdlib>
#include <fstream>
#include <functional>
#include <iomanip>
#include <iostream>
#include <iterator>
#include <list>
#include <sstream>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <vector>
using namespace std;
#endif  //CALC_ERROR_H

void ClearScreen();				//Clears the screen.
void Pause();					  //Waits for user response.
bool evenlyDivisibleByTwo(int i);  //Returns true if number is an even number.

//************************************
//Clear Screen.
//************************************
void ClearScreen()
{
system( "CLS" );
cout << endl << endl << endl;
}

//************************************
//Pause.
//************************************
void Pause()
{
cout << endl << endl << endl;
cout << "  ";
system( "PAUSE" );
}

//************************************
//Unary Predicate Function:
//Returns true if number is more than
//30.
//************************************
//bool isMoreThan30( int value )
//{
//   return value > 30;
//}

//************************************
//Unary Predicate Function:
//Returns true if number is
//divisible by 3.
//************************************
bool isDivisibleBy3(int i)
{
if((i%3) == 0) return true;

return false;
}

//************************************
// MAIN() FUNCTION.
//************************************
int main(int argc, char* argv[])
{
ClearScreen();

//Instantiate object myList.
list<int> myList;

//Insert list elements.
for ( int i=6; i<=20; ++i )
{
myList.push_back( i );
if ( isDivisibleBy3( i ) )
{
cout << "  " << i;
}
}

//Instantiate iterator.
list<int>::iterator myIt;

cout << "  are the " << count_if(myList.begin(), myList.end(), isDivisibleBy3);
cout << " numbers divisible by 3.  ";

Pause();
return EXIT_SUCCESS;
}

```

3. VECTOR EXAMPLE

The syntax for instantiating a vector object is as follows:

vector <type> objectName;

vector is a C++ keyword. The angle brackets contain the word type <type> which is a placeholder for the type of the vector you are instantiating. objectName is the name of the vector object you are instantiating.

When working with a vector the count_if() functions three parameters are as follows:

a. objectName.begin() sets the vector element starting point.
begin() is a function that automatically moves the pointer to the first element of the vector.

b. objectName.end() sets the vector element ending point.
end() is a function that automatically works with the begin() function to establish a range of vector elements which will be tested for the condition of the unary predicate. In this case the range is from the first element of the vector to the last element of the vector.

c. Unary Predicate

The unary predicate is established by the programmer by writing a Boolean function which returns the appropriate condition for the count_if() function. The attached vector example program unary predicate function name is evenlyDivisibleByTwo.

Attached is the vector example program:

```//**************************************
//C++ STL PREDICATE FUNCTIONS TUTORIAL
//Vector Example:
//**************************************
#ifndef CALC_ERROR_H
#define CALC_ERROR_H
#include <algorithm>
#include <cstdlib>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <vector>
using namespace std;
#endif  //CALC_ERROR_H

void ClearScreen();				//Clears the screen.
void Pause();					  //Waits for user response.
bool evenlyDivisibleByTwo(int i);  //Returns true if number is an even number.

//************************************
//Clear Screen.
//************************************
void ClearScreen()
{
system( "CLS" );
cout << endl << endl << endl;
}

//************************************
//Pause.
//************************************
void Pause()
{
cout << endl << endl << endl;
cout << "  ";
system( "PAUSE" );
}

//************************************
//Unary Predicate Function:
//Returns true if number is an even
//number.
//************************************
bool evenlyDivisibleByTwo( int i )
{
return !( i%2 );
}

//************************************
// MAIN() FUNCTION.
//************************************
int main(int argc, char* argv[])
{
ClearScreen();

vector< int > VO;

int i;

for( i = 1; i < 40; i++ )
VO.push_back( i );

cout << "  The even numbers are: ";
for(i = 0; i < VO.size(); i++)
{
if (evenlyDivisibleByTwo( VO[ i ] ))
{
cout << VO[ i ] << " ";
}
}
cout << endl << endl;

i = count_if(VO.begin(), VO.end(), evenlyDivisibleByTwo);
cout << "  " << i << " TOTAL" << endl;

Pause();

return EXIT_SUCCESS;
}

```

 III. WRITING UNARY PREDICATES

The following must be taken into consideration when writing predicates:

A. A unary predicate is called like a function; therefore, a unary predicate must be callable.

B. A unary predicate must accept one argument and return a value that is convertible to Boolean. One argument is supplied when the predicate is called. The return value is used as a conditional expression and must be convertible to type bool.

C. The predicate must not modify its argument. A unary predicate must not modify the elements in the input sequence that it receives as an argument. The unary predicate can inspect the sequence elements, but it must not modify them.

D. Unary predicates logic must not be dependent on the order in which sequence elements are supplied to it.

Is This A Good Question/Topic? 1

Page 1 of 1

 .related ul { list-style-type: circle; font-size: 12px; font-weight: bold; } .related li { margin-bottom: 5px; background-position: left 7px !important; margin-left: -35px; } .related h2 { font-size: 18px; font-weight: bold; } .related a { color: blue; }