STL Sort Algorithm

The sort algorithm is an operation (function) that can be applied to many STL containers (with the notable exception of the list container). For now, we will consider its use only with the vector container class template. It can be used in the following way:

#include <vector>
#include <algorithm>  // Include algorithms
using namespace std;

vector<int> vec;
vec.push_back (10);
vec.push_back (3);
vec.push_back (7);

sort(vec.begin(), vec.end()); // Sort the vector

// The vector now contains: 3, 7, 10 

The sort algorithm orders the container's contents in ascending order, as defined by the "less than" (<) operator as applied to the vector elements. If this operator is defined for a programmer-defined type (as is the case with the string class), then the programmer-defined type can be sorted just as easily as a built-in type.




Copyright 2002 by Patrick Meier
Last updated on 26.08.2002 by Patrick Meier