Algorithm Interfaces |
sort()
only works with random access iterators. Because a
vector has random access iterators, the following example compiles and works
correctly.
#include <iostream>
#include <algorithm>
#include <vector>
void
main()
{
vector< int > years;
years.push_back( 1962 );
years.push_back( 1992 );
years.push_back( 2001 );
years.push_back( 1999 );
sort( years.begin(), years.end() );
vector< int >::iterator i;
for ( i = years.begin(); i != years.end(); ++i )
cout << *i << "\n";
}
1962
1992
1999
2001
If sort()
is used with a less powerful iterator, either a compiler error or a linker
error occurs. The following example results in a compiler error, because sort()
is attempted on a list that provides only bidirectional iterators.
#include <iostream>
#include <algorithm>
#include <list>
// NOTE: This example is NOT supposed to compile.
void
main()
{
list< int > years;
years.push_back( 1962 );
years.push_back( 1992 );
years.push_back( 2001 );
years.push_back( 1999 );
sort( years.begin(), years.end() ); // Causes linker error.
list< int >::iterator i;
for ( i = years.begin(); i != years.end(); ++i )
cout << *i << "\n";
}
Many STL
algorithms require a predicate, function, or function object as a parameter.
For example, the for_each()
algorithm applies a supplied function to every item in a sequence. Similarly,
the count_if()
algorithm counts all the elements in a sequence satisfying a particular
predicate. For examples and further information about predicates and function
objects, consult the Functions and Function Objects
.
Copyright©1994-2026 Recursion
Software LLC
All Rights Reserved - For use by licensed users only.