Click Here For A Free vLab!
home account info subscribe login search FAQ/help site map contact us


 
Brief Full
 Advanced
      Search
 Search Tips
[an error occurred while processing this directive]
Previous Table of Contents Next



To test the member function, you can execute the following program:
// This is the program to test
// persname class
// pn1test.cpp

#include <iostream>
#include “persnam1.h”

int main()
{

    persname Names;

    Names.Add (“Andrew”);
    Names.Add (“Peter”);
    Names.Add (“John”);
    Names.Add (“Andrew”);
    Names.Add (“Andrew”);
    Names.Add (“Margaret”);

    Names.Sort();
    Names.DisplayAll();
    cout << endl;

// The following lines are new; they show the usage of FindNameJ
    cout << “The first name  starting with J is “
      << Names.FindNameJ() << endl;
return 0;
}

The program should return
Andrew
Andrew
Andrew
Andrew
John
Margaret
Peter

The first name starting with J is John
3.  Create a method that uses a predicate with the unique algorithm
There is no _if version of the unique algorithm. Instead, unique is an overloaded name. Another function accepts a binary predicate as an argument.
Let’s write a program that removes all names starting with the same letter except the first one. The new member function of the persname class will have the following declaration and definition:
// Leaves one word per letter
void RemoveA (void);

and
class SameLetter:binary_function <string, string, bool>
{
public:
    bool operator()(const string& a, const string& b) {
        if (a.at(0) == b.at(0))
            return true;
        else
            return false;
    }
};
    // Leaves one word per letter
void persname::RemoveA (void)
{
    list <string>::iterator new_end;
    new_end = unique(PName.begin(), PName.end(), SameLetter());
    PName.erase(new_end, PName.end());
}

Because the unique algorithm does not truncate the list, the erase list member function must be used.
The class SameLetter defines the function object that specifies the new equality function. In the unique algorithm, two consecutive elements of the list are considered equal if the result of this function is true.
The SameLetter function is also called a binary predicate.

Comments

To increase the functionality of certain algorithms, you can use predicates to specify the criteria that the algorithm uses when processing data. A few algorithms change their names by adding the _if suffix. Other algorithms are overloaded and use the same names.

Predicates can be unary or binary depending on the number of arguments. A predicate is a function that results in truth or falsehood depending on certain conditions. Functions that change their names with _if, such as count_if and find_if, accept unary predicates. Functions that use overloaded names, such as unique, accept binary predicates.

The use of predicates dramatically increases the power of algorithms. It almost doubles their number and provides a programmer with the ability to embed his own functions in the standard algorithms.

9.3 Repeat an action with all elements in a container range?

Problem

I want to be able to apply a certain function to an entire container or to the range of a container. For example, I often have to convert an area from square feet to square meters and print the results. Do I have to use for loops or is there another way of coding?

Technique

The Standard Template Library has an analog of the C++ for statement. This is the for_each algorithm that can be applied to any sequential container. Moreover, the algorithm can work on any data structure that has a sequential order similar to an array.

The for_each algorithm applies the specified function in forward order, from the beginning to the end of the range. In this How-To, you will write a few examples to show the for_each algorithm functionality.

Steps

1.  Using for_each algorithm with arrays
You want to create a program that converts square feet to square meters. The original C++ program is written with arrays and uses the standard C++ for statement.
// fe1.cpp

#include <iostream>
#include <iomanip>
using namespace std;

int main()
{
    const double factor = 0.09290304;
    double area[]= {1200.0, 1080.78, 981.5, 224.70};

    for (int i = 0; i < 4; i++)
    {
         cout << setprecision(2) << setiosflags(ios::fixed) <<
             factor*area[i] << endl;
    }
return 0;
}

To use the STL for_each algorithm, you have to define the function you are going to use in the loop. Let’s create the PrintM function that will convert the value in square feet to square meters and print the result.
Note that for_each is a nonmutative algorithm. It should not accept the functions that change the content of the container.
// fe1.cpp

#include <iostream>
#include <iomanip>
#include <algorithm>
using namespace std;
void PrintM(double valueF)
{
    const double factor = 0.09290304;
    cout << setprecision(2) << setiosflags(ios::fixed) <<
       factor*valueF << endl;
}

int main()
{
    double areaF[]= {1200.0, 1080.78, 981.5, 224.70};

    for_each (areaF, areaF + 4, PrintM);
return 0;

}

The beginning and the end of the sorting range are areaF and areaF+4. Note that areaF+4 points after the last element of the array.
The <algorithm> header file is required for all STL algorithms.
The output of the program should be
111.48
100.41
91.18
20.88


Previous Table of Contents Next


Products |  Contact Us |  About Us |  Privacy  |  Ad Info  |  Home

Use of this site is subject to certain Terms & Conditions, Copyright © 1996-1999 EarthWeb Inc.
All rights reserved. Reproduction whole or in part in any form or medium without express written permision of EarthWeb is prohibited.