In addition to container classes and iterators,
STL also provides a number of generic algorithms for working with the elements of the container classes.
These allow you to do things like search, sort, insert, reorder, remove, and copy elements of the container class.
To use any of the STL algorithms, simply include the algorithm header file.
min_element and max_element
The min_element and max_element algorithms find the min and max element in a container class:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
#include <iostream> #include <list> #include <algorithm> int main() { using namespace std; list< int > li; for ( int nCount=0; nCount < 6; nCount++) li.push_back(nCount); list< int >::const_iterator it; // declare an iterator it = min_element(li.begin(), li.end()); cout << *it << " " ; it = max_element(li.begin(), li.end()); cout << *it << " " ; cout << endl; } |
Prints:
0 5
find (and list::insert)
In this example, we’ll use the find() algorithm to find a value in the list class, and then use the list::insert() function to add a new value into the list at that point.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
#include <iostream> #include <list> #include <algorithm> int main() { using namespace std; list< int > li; for ( int nCount=0; nCount < 6; nCount++) li.push_back(nCount); list< int >::const_iterator it; // declare an iterator it = find(li.begin(), li.end(), 3); // find the value 3 in the list li.insert(it, 8); // use list::insert to insert the value 8 before it for (it = li.begin(); it != li.end(); it++) // for loop with iterators cout << *it << " " ; cout << endl; } |
This prints the value
0 1 2 8 3 4 5
sort and reverse
In this example, we’ll sort a vector and then reverse it.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
#include <iostream> #include <vector> #include <algorithm> int main() { using namespace std; vector< int > vect; vect.push_back(7); vect.push_back(-3); vect.push_back(6); vect.push_back(2); vect.push_back(-5); vect.push_back(0); vect.push_back(4); sort(vect.begin(), vect.end()); // sort the list vector< int >::const_iterator it; // declare an iterator for (it = vect.begin(); it != vect.end(); it++) // for loop with iterators cout << *it << " " ; cout << endl; reverse(vect.begin(), vect.end()); // reverse the list for (it = vect.begin(); it != vect.end(); it++) // for loop with iterators cout << *it << " " ; cout << endl; } |
This produces the result:
-5 -3 0 2 4 6 7
7 6 4 2 0 -3 -5
Note that sort() doesn’t work on list container classes .
ref : http://www.learncpp.com/cpp-tutorial/117-multiple-inheritance/