beautypg.com

Merge two adjacent sequences into one – HP Integrity NonStop H-Series User Manual

Page 162

background image

while (next_permutation(start, start + 3));

// example 2, permute words
char * words = {"Alpha", "Beta", "Gamma"};
do
copy (words, words + 3,
ostream_iterator (cout, " ")), cout << endl;
while (next_permutation(words, words + 3, nameCompare));

// example 3, permute characters backwards
char * word = "bela";
do
cout << word << ' ';
while (prev_permutation (word, &word[4]));
cout << endl;
}

Example 3 in the sample program illustrates the use of the reverse permutation algorithm, which
generates values in reverse sequence. This example also begins in the middle of a sequence, rather
than at the beginning. The remaining permutations of the word "bela," are beal, bale, bael, aleb,
albe, aelb, aebl, able, and finally, abel.

Merge Two Adjacent Sequences into One

A merge takes two ordered sequences and combines them into a single ordered sequence,
interleaving elements from each collection as necessary to generate the new list. The
inplace_merge() algorithm assumes a sequence is divided into two adjacent sections, each of which
is ordered. The merge combines the two sections into one, moving elements as necessary. (The
alternative merge() algorithm, described elsewhere, can be used to merge two separate sequences
into one.) The arguments to inplace_merge() must be bidirectional iterators.

void inplace_merge (BidirectionalIterator first,
BidirectionalIterator middle,
BidirectionalIterator last [, BinaryFunction ] );

The example program illustrates the use of the inplace_merge() algorithm with a vector and with a
list. The sequence 0 2 4 6 8 1 3 5 7 9 is placed into a vector. A find() call (

Find an Element

Satisfying a Condition

) is used to locate the beginning of the odd number sequence. The two calls

on inplace_merge() then combine the two sequences into one.

void inplace_merge_example ()
// illustrate the use of the inplace_merge algorithm
{
// first generate the sequence 0 2 4 6 8 1 3 5 7 9
vector numbers(10);
for (int i = 0; i < 10; i++)
numbers[i] = i < 5 ? 2 * i : 2 * (i - 5) + 1;

This manual is related to the following products: