| Category: algorithms | Component type: function |
template <class RandomAccessIterator>
void stable_sort(RandomAccessIterator first, RandomAccessIterator last);
template <class RandomAccessIterator, class StrictWeakOrdering>
void stable_sort(RandomAccessIterator first, RandomAccessIterator last,
StrictWeakOrdering comp);
The two versions of stable_sort differ in how they define whether one element is less than another. The first version compares objects using operator<, and the second compares objects using a function object comp.
inline bool lt_nocase(char c1, char c2) { return tolower(c1) < tolower(c2); }
int main()
{
char A[] = "fdBeACFDbEac";
const int N = sizeof(A) - 1;
stable_sort(A, A+N, lt_nocase);
printf("%s\n", A);
// The printed result is ""AaBbCcdDeEfF".
}
[1] Note that two elements may be equivalent without being equal. One standard example is sorting a sequence of names by last name: if two people have the same last name but different first names, then they are equivalent but not equal. This is why stable_sort is sometimes useful: if you are sorting a sequence of records that have several different fields, then you may want to sort it by one field without completely destroying the ordering that you previously obtained from sorting it by a different field. You might, for example, sort by first name and then do a stable sort by last name.
[2] Stable_sort uses the merge sort algorithm; see section 5.2.4 of Knuth. (D. E. Knuth, The Art of Computer Programming. Volume 3: Sorting and Searching. Addison-Wesley, 1975.)
| Contact Us | Site Map | Trademarks | Privacy | Using this site means you accept its Terms of Use |
| Copyright © 1993-2006 Silicon Graphics, Inc. All rights reserved. |