Skip to main content

9.2) Algorithm Examples: Sorting A Container's Elements


vector<int> v;
...
sort(v.begin(), v.begin() + 10);            // first 10 elements, ascending
sort(v.end() - 15, v.end());                // last 15 elements, ascending
sort(v.begin(), v.end());                   // all elements, ascending
sort(v.begin(), v.end(), greater<int>());   // all elements, descending
  • Default version requires that the < operator has a meaning for the values in the container (which will be the case for all the built-in types of C++)
  • Advanced version requires a comparison function as a third argument; C++ provides standard comparison function templates for the common cases (such as greater<int>() in this example)
  • See sortdemo.cpp for a complete example program