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

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
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
can be applied to a vector holding an ordered
collection. For example, two vectors can be merged using the generic algorithm merge() (
).
// merge two vectors, printing output
merge (vecOne.begin(), vecOne.end(), vecTwo.begin(), vecTwo.end(),
ostream_iterator
Sorting a vector also lets us use the more efficient binary search algorithms (
), instead of a linear traversal algorithm such as find().
Useful Generic Algorithms
Most of the algorithms described in
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
max_element (vec_five.begin(), vec_five.end());
cout << "maximum is " << *where << endl;
Purpose
Name
Fill a vector with a given initial value
fill