Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Comparator is not used in median_index #2

Closed
Morwenn opened this issue Jan 23, 2021 · 3 comments
Closed

Comparator is not used in median_index #2

Morwenn opened this issue Jan 23, 2021 · 3 comments

Comments

@Morwenn
Copy link

Morwenn commented Jan 23, 2021

I was trying to replace my use of std::nth_element with miniselect's implementation of Andrei Alexandrescu's adaptive quickselect, but I ran into an issue while doing so: it seems that one of the median_index overloads does not consistently use the given comparator to compare elements (lines marked with HERE):

template <class Iter, class Compare,
          class DiffType = typename std::iterator_traits<Iter>::difference_type>
inline DiffType median_index(const Iter r, DiffType a, DiffType b, DiffType c,
                             Compare&& comp) {
  if (r[a] > r[c]) std::swap(a, c); // HERE
  if (r[b] > r[c]) return c; // HERE
  if (comp(r[b], r[a])) return a;
  return b;
}

I stumbled upon this issue while trying to sort with a custom predicate a collection of a type that doesn't have comparison operators, so I fortunately got into a compile-time error, but I believe that it can result into more subtle runtime errors too when the types to sort do implement comparison operators.

Anyway, thanks again for this library, I'm glad to see selection algorithms getting some love 😄

@danlark1
Copy link
Owner

Thanks, will fix shortly !

@danlark1
Copy link
Owner

0.4.0 fixed, thank you. Everybody should use this version, my bad I didn't notice and somehow testing did not catch the failure -- in one test I was comparing pointers and all sanitizers were good :(

@Morwenn
Copy link
Author

Morwenn commented Jan 23, 2021

No problem, I plan to use the algorithm to replace libc++'s nth_element in one of my rather well-tested projects - I only noticed recently that it was O(n²) -, so I will tell you if I find anything else. Thanks for the quick fix 🙂

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants