Skip to content

Commit acaea71

Browse files
committed
stable_sort: stability test (keep relative order)
1 parent 3c17883 commit acaea71

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
@@ -204,6 +204,36 @@ _LIBCPP_CONSTEXPR_SINCE_CXX23 void test_larger_sorts() {
204204
test_larger_sorts<N, N>();
205205
}
206206

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

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

0 commit comments

Comments
 (0)