Skip to content

Instantly share code, notes, and snippets.

@Liam0205
Last active January 5, 2018 11:53
Show Gist options
  • Save Liam0205/1b3c8499d99d08d885dc595edecc5458 to your computer and use it in GitHub Desktop.
Save Liam0205/1b3c8499d99d08d885dc595edecc5458 to your computer and use it in GitHub Desktop.
`std::sort` does not perserve the order of elements within equal values, however the result of it is of no randomness.
#include <iostream>
#include <algorithm>
#include <vector>
#include <utility>
#include <random>
namespace {
const constexpr size_t kTestLen = 1000000;
std::random_device rd;
std::mt19937 urbg(rd());
using FirstT = size_t;
using SecondT = size_t;
using PairT = std::pair<FirstT, SecondT>;
} // namespace
namespace std {
template <> struct less<PairT> {
inline constexpr bool operator()(const PairT& lhs, const PairT& rhs) const {
return lhs.first < rhs.first;
}
};
} // namespace std
int main() {
std::vector<PairT> round_one;
round_one.reserve(kTestLen);
for (size_t i = 0; i != kTestLen; ++i) {
round_one.emplace_back(i / 3, i);
}
std::shuffle(round_one.begin(), round_one.end(), urbg);
std::vector<PairT> round_two(round_one);
std::less<PairT> pair_less;
std::sort(round_one.begin(), round_one.end(), pair_less);
std::sort(round_two.begin(), round_two.end(), pair_less);
std::cout << (round_one == round_two) << std::endl;
return 0;
}
@Liam0205
Copy link
Author

Liam0205 commented Jan 5, 2018

Compile and execute by:

g++ -std=c++11 -O3 stability_test_of_std_sort.cc -o stability_test_of_std_sort
./stability_test_of_std_sort

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment