2

I tried to sort some values (ints here) by related timestamps, with lambda as comparator:

vector<pair<unsigned long long,int>> v = {
    {1541518270397ull,0},
    {1541518270396ull,0},
    {1541518270394ull,0},
    {1541518270395ull,0},
    {1541518270385ull,0},
    {1541518270391ull,0},
    {1541518270390ull,0},
    {1541518270392ull,0},
    {1541518270386ull,0},
    {1541518270393ull,0},
    {1541518270389ull,0},
    {1541518270388ull,0},
    {1541518270401ull,0},
    {1541518270398ull,0},
    {1541518270399ull,0},
    {1541518270400ull,0},
    {1541518270402ull,0},
    {1541518270403ull,0}
};

std::sort(v.begin(), v.end(), [](const auto& p1, const auto& p2){ return p2.first >= p1.first; });
for (const auto& e : v) cout << e.first << endl;

(I know that std::less would do the job here. My real code does more complex things, but this example triggers the same problem). When compiled with Apple LLVM version 9.1.0 (clang-902.0.39.2), -std=c++14 -stdlib=libc++ this code produces wrong (?) output:

1541518270385
1541518270386
1541518270388
1541518270389
1541518270390
1541518270391
1541518270392
1541518270394
1541518270401 <------ here
1541518270395
1541518270393 <------ and here
1541518270396
1541518270397
1541518270398
1541518270399
1541518270400
1541518270402
1541518270403

The order is as expected when I run it on GCC. What am i missing?

puhacz
  • 53
  • 4
  • 1
    Slightly counter intuitively to sort in reverse order you need to use `>` rather than `! <`/`>=`, see the duplicate – Alan Birtles Nov 06 '18 at 16:40
  • Your comparison function is not a strict weak ordering. You return both `true` and `false` if the quantities are equal but given to you in a different order. – PaulMcKenzie Nov 06 '18 at 16:42
  • See https://stackoverflow.com/questions/38966516/should-sorting-algorithm-pass-same-element-in-the-comparison-function for why libc++ is comparing elements with themselves (which is why this only fails on libc++ as none of your elements have the same value) – Alan Birtles Nov 06 '18 at 16:53

0 Answers0