C++ examples for STL Algorithm:sort
Use sort() on a vector with natural order and descending order.
#include <cstdlib> #include <iostream> #include <vector> #include <functional> #include <algorithm> using namespace std; void show(const char *msg, vector<int> vect); int main()//from w w w . j ava 2 s .c om { vector<int> v(10); // Initialize v with random values. for(unsigned i=0; i < v.size(); i++) v[i] = rand() % 100; show("Original order:\n", v); cout << endl; // Sort the entire container. sort(v.begin(), v.end()); show("Order after sorting into natural order:\n", v); cout << endl; // Now, sort into descending order by using greater(). sort(v.begin(), v.end(), greater<int>()); show("Order after sorting into descending order:\n", v); cout << endl; // Sort a subset of the container sort(v.begin()+2, v.end()-2); show("After sorting elements v[2] to v[7] into natural order:\n", v); return 0; } void show(const char *msg, vector<int> vect) { cout << msg; for(unsigned i=0; i < vect.size(); ++i) cout << vect[i] << " "; cout << "\n"; }