list::sort | public member function |
void sort ( ); template <class Compare> void sort ( Compare comp ); |
Sort elements in container
Sorts the elements in the container from lower to higher. The sorting is performed by comparing the elements in the container in pairs using a sorting algorithm.
In the first version, taking no parameters, the comparisons are performed using the operator< between the elements being compared.
In the second version, the comparisons are perfomed using function comp, which performs weak strict ordering (this basically means the comparison operation has to be transitive and irreflexive).
The entire operation does not involve the construction or destruction of any element object.
Parameters
- comp
- Comparison function that, taking two values of the same type than those contained in the list object, returns true if the first argument goes before the second argument in the specific order (i.e., if the first is less than the second), and false otherwise.
Return value
noneExample
// list::sort #include <iostream> #include <list> #include <string> #include <cctype> using namespace std; // comparison, not case sensitive. bool compare_nocase (string first, string second) { unsigned int i=0; while ( (i<first.length()) && (i<second.length()) ) { if (tolower(first[i])<tolower(second[i])) return true; ++i; } if (first.length()<second.length()) return true; else return false; } int main () { list<string> mylist; list<string>::iterator it; mylist.push_back ("one"); mylist.push_back ("two"); mylist.push_back ("Three"); mylist.sort(); cout << "mylist contains:"; for (it=mylist.begin(); it!=mylist.end(); ++it) cout << " " << *it; cout << endl; mylist.sort(compare_nocase); cout << "mylist contains:"; for (it=mylist.begin(); it!=mylist.end(); ++it) cout << " " << *it; cout << endl; return 0; } |
Output:
mylist contains: Three one two |
Using the function compare_nocase the comparison is made case insensitive.
Complexity
Approximately NlogN where N is the list size.See also
list::merge | Merge sorted lists (public member function) |
list::reverse | Reverse the order of elements (public member function) |
list::unique | Remove duplicate values (member function) |