Topic: | Sorting (STL) |
---|---|
Author: | Peter Bui <pbui@cse.nd.edu> |
Date: | September 23, 2009 |
Included in <algorithm> are a variety of sorting functions:
sort(vec.begin(), vec.end());
partial_sort(vec.begin(), vec.begin() + 5, vec.end());
partial_sort(vec.begin(), vec.end(), vec.end());
stable_sort(lst.begin(), lst.end());
Customize sort order with binary predicates:
bool less_length(const string &s1, const string &s2)
{
return s1.length() < s2.length();
}
bool compare_jobs(const struct job *j1, const struct job *j2)
{
return j1->priority < j2->priority;
}
sort(vStrings.begin(), vStrings.end(), less_length);
sort(lJobs.begin(), lJobs.end(), compare_jobs);
Included in <functional> are a variety of function objects:
sort(vInts.begin(), vInts.end(), greater<int>());
nth_element(vDists.begin(), vDists.begin() + nth, vDists.end());
// Convert to heap
make_heap(v.begin(), v.end());
// Pop next element out of heap
pop_heap(v.begin(), v.end());
v.pop_back();
// Push new element into heap
v.push_back(7);
push_heap(v.begin(), v.end());
// Convert help to ordered collection
sort_heap(v.begin(), v.end());