function template
<algorithm>
std::stable_sorttemplate <class RandomAccessIterator> void stable_sort ( RandomAccessIterator first, RandomAccessIterator last );template <class RandomAccessIterator, class Compare> void stable_sort ( RandomAccessIterator first, RandomAccessIterator last, Compare comp );
Sort elements preserving order of equivalents
Sorts the elements in the range[first,last)
into ascending order, like sort, but stable_sort preserves the relative order of the elements with equivalent values.
The elements are compared using operator<
for the first version, and comp for the second.
[first,last)
, which contains all the elements between first and last, including the element pointed by first but not the element pointed by last.
bool
. The value returned indicates whether the element passed as first argument is considered to go before the second in the specific strict weak ordering it defines.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
// stable_sort example
#include <iostream> // std::cout
#include <algorithm> // std::stable_sort
#include <vector> // std::vector
bool compare_as_ints (double i,double j)
{
return (int(i)<int(j));
}
int main () {
double mydoubles[] = {3.14, 1.41, 2.72, 4.67, 1.73, 1.32, 1.62, 2.58};
std::vector<double> myvector;
myvector.assign(mydoubles,mydoubles+8);
std::cout << "using default comparison:";
std::stable_sort (myvector.begin(), myvector.end());
for (std::vector<double>::iterator it=myvector.begin(); it!=myvector.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
myvector.assign(mydoubles,mydoubles+8);
std::cout << "using 'compare_as_ints' :";
std::stable_sort (myvector.begin(), myvector.end(), compare_as_ints);
for (std::vector<double>::iterator it=myvector.begin(); it!=myvector.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
return 0;
}
Possible output:
using default comparison: 1.32 1.41 1.62 1.73 2.58 2.72 3.14 4.67 using 'compare_as_ints' : 1.41 1.73 1.32 1.62 2.72 2.58 3.14 4.67
N*log2(N)
element comparisons (where N is this distance), and up to that many element moves.
N*log22(N)
element comparisons, and up to that many element swaps.
[first,last)
are modified.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4