Created
June 8, 2017 07:59
-
-
Save BillyONeal/529a4696d3daeeadc4e8a1c7964d6a59 to your computer and use it in GitHub Desktop.
Sort Determinisim
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <assert.h> | |
#include <stdio.h> | |
#include <algorithm> | |
#include <random> | |
#include <vector> | |
using namespace std; | |
struct kv { | |
unsigned int significant; | |
unsigned int insignificant; | |
}; | |
inline bool operator<(const kv& lhs, const kv& rhs) { | |
return lhs.significant < rhs.significant; | |
} | |
int main() { | |
vector<kv> values(1'000); | |
for (size_t idx = 0; idx < 1'000; ++idx) { | |
values[idx].significant = idx / 2; | |
values[idx].insignificant = idx; | |
} | |
random_device rd; | |
shuffle(values.begin(), values.end(), rd); | |
vector<kv> valuesCopy = values; | |
sort(values.begin(), values.end()); | |
sort(valuesCopy.begin(), valuesCopy.end()); | |
// if this assert can fail, sort is nondeterministic | |
assert(memcmp(values.data(), valuesCopy.data(), 1'000 * sizeof(kv)) == 0); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment