Skip to content

Commit 55c19d3

Browse files
committed
stable_sort: stability test (keep relative order)
1 parent 26d5a32 commit 55c19d3

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

libcxx/test/std/algorithms/alg.sorting/alg.sort/stable.sort/stable_sort.pass.cpp

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -205,6 +205,36 @@ _LIBCPP_CONSTEXPR_SINCE_CXX23 void test_larger_sorts() {
205205
test_larger_sorts<N, N>();
206206
}
207207

208+
namespace stability_test {
209+
struct Element {
210+
int key;
211+
int value;
212+
_LIBCPP_CONSTEXPR_SINCE_CXX23 Element(int key, int value) : key(key), value(value) {}
213+
_LIBCPP_CONSTEXPR_SINCE_CXX23 bool operator==(const Element other) const {
214+
return (key == other.key) and (value == other.value);
215+
}
216+
};
217+
218+
struct Comparer_by_key {
219+
_LIBCPP_CONSTEXPR_SINCE_CXX23 bool operator()(const Element lhs, const Element rhs) { return lhs.key < rhs.key; }
220+
};
221+
222+
_LIBCPP_CONSTEXPR_SINCE_CXX23 std::array<Element, 5> get_by_key_sorted_array() {
223+
std::array<Element, 5> a = {Element(1, 0), Element(1, 1), Element(0, 0), Element(0, 1), Element(0, 2)};
224+
std::stable_sort(a.begin(), a.end(), Comparer_by_key());
225+
return a;
226+
}
227+
228+
_LIBCPP_CONSTEXPR_SINCE_CXX23 void run() {
229+
_LIBCPP_CONSTEXPR_SINCE_CXX23 std::array<Element, 5> a = get_by_key_sorted_array();
230+
COMPILE_OR_RUNTIME_ASSERT(a[0] == Element(0, 0));
231+
COMPILE_OR_RUNTIME_ASSERT(a[1] == Element(0, 1));
232+
COMPILE_OR_RUNTIME_ASSERT(a[2] == Element(0, 2));
233+
COMPILE_OR_RUNTIME_ASSERT(a[3] == Element(1, 0));
234+
COMPILE_OR_RUNTIME_ASSERT(a[4] == Element(1, 1));
235+
}
236+
} // namespace stability_test
237+
208238
#if _LIBCPP_STD_VER >= 23
209239
# define COMPILE_AND_RUNTIME_CALL(func) \
210240
func; \
@@ -245,6 +275,10 @@ int main(int, char**) {
245275
test_larger_sorts<1009>();
246276
}
247277

278+
{ // test "stable" aka leaving already sorted elements in relative order
279+
COMPILE_AND_RUNTIME_CALL(stability_test::run());
280+
}
281+
248282
#ifndef TEST_HAS_NO_EXCEPTIONS
249283
{ // check that the algorithm works without memory
250284
std::vector<int> vec(150, 3);

0 commit comments

Comments
 (0)