Swap values from two parallel ranges – HP Integrity NonStop H-Series User Manual

Page 148

Advertising
background image

char labelBuffer[80];
ostrstream ost(labelBuffer, 80);
ost << "L_" << lastLabel++ << '\0';
return string(labelBuffer);
}

void generate_example ()
// illustrate the use of the generate and generate_n algorithms
{
// example 1, generate a list of label values
list<string> labelList;
generate_n (inserter(labelList, labelList.begin()),
4, generateLabel);

// example 2, generate an arithmetic progression
vector<int> iVec(10);
generate (iVec.begin(), iVec.end(), iotaGen(2));
generate_n (iVec.begin(), 5, iotaGen(7));
}

A generator can be constructed as a simple function that "remembers" information about its
previous history in one or more static variables. An example is shown in the beginning of the
example program, where the function generateLabel() is described. This function creates a sequence
of unique string labels, such as might be needed by a compiler. Each invocation on the function
generateLabel() results in a new string of the form L_ddd, each with a unique digit value. Because
the variable named lastLabel is declared as static, its value is remembered from one invocation to
the next. The first example of the sample program illustrates how this function might be used in
combination with the generate_n() algorithm to initialize a list of four label values.

As we described in Chapter 3, in the Standard Library a function is any object that will respond to
the function call operator. Using this fact, classes can easily be constructed as functions. The class
iotaGen, which we described in

Chapter 3 (

Functions

)

, is an example. The iotaGen function object

creates a generator for an integer arithmetic sequence. In the second example in the sample
program, this sequence is used to initialize a vector with the integer values 2 through 11. A call on
generate_n() is then used to overwrite the first 5 positions of the vector with the values 7 through
11, resulting in the vector 7 8 9 10 11 7 8 9 10 11.

Swap Values from Two Parallel Ranges

The template function swap() can be used to exchange the values of two objects of the same type. It
has the following definition:

template <class T> void swap (T& a, T& b)
{
T temp(a);
a = b;
b = temp;
}

Advertising
This manual is related to the following products: