beautypg.com

Sorting and sorted vector operations, Useful generic algorithms – HP Integrity NonStop H-Series User Manual

Page 61

background image

if (num)
cout << "contains a 17" << endl;
else
cout << "does not contain a 17" << endl;

Initializing Count

Sorting and Sorted Vector Operations

A vector does not automatically maintain its values in sequence. However, a vector can be placed in
order using the generic algorithm sort() (

Chapter 14, Sorting Algorithms

). The simplest form of sort

uses for its comparisons the less-than operator for the element type. An alternative version of the
generic algorithm permits the programmer to specify the comparison operator explicitly. This can
be used, for example, to place the elements in descending rather than ascending order:

// sort ascending
sort (aVec.begin(), aVec.end());

// sort descending, specifying the ordering function explicitly
sort (aVec.begin(), aVec.end(), greater() );

// alternate way to sort descending
sort (aVec.rbegin(), aVec.rend());

A number of the operations described in

Chapter 14

can be applied to a vector holding an ordered

collection. For example, two vectors can be merged using the generic algorithm merge() (

Chapter

14, Merge Ordered Sequences

).

// merge two vectors, printing output
merge (vecOne.begin(), vecOne.end(), vecTwo.begin(), vecTwo.end(),
ostream_iterator (cout, " "));

Sorting a vector also lets us use the more efficient binary search algorithms (

Chapter 14, Binary

Search

), instead of a linear traversal algorithm such as find().

Useful Generic Algorithms

Most of the algorithms described in

Chapter 13

can be used with vectors. The following table

summarizes a few of the more useful of these. For example, the maximum value in a vector can be
determined as follows:

vector::iterator where =
max_element (vec_five.begin(), vec_five.end());
cout << "maximum is " << *where << endl;

Purpose

Name

Fill a vector with a given initial value

fill

This manual is related to the following products: