0

I was using the sort function in Armadillo library but it kept firing NaN errors which were nonexistent when I checked manually... So I switched to STL sort function and it worked! So my curiosity is, how does STL sort function treat NaNs?

  • 1
    Comparisons in the standard library work on the basis of a "strict weak ordering" enforced by `operator<`. – Jesper Juhl Feb 09 '20 at 18:29
  • The way that `sort()` works is documented, though there are variants as free function and as memberfunction. Which one do you mean? What questions do you have that isn't answered in e.g. cppreference.com? Also, what code were you using for either framework? Be sure to supply a [mcve] for each. Also, what were your observations that lead you to the conclusion it had anything to do with NaNs? As a new user, also take the [tour] and read [ask]. – Ulrich Eckhardt Feb 09 '20 at 18:29

1 Answers1

9

Does C++ STL sort check for NaN?

std::sort uses the comparison function that you provide for it. If your function "checks for NaN", then so does std::sort does so through the comparison function. If you don't provide a comparison function, then std::less is used by default. That uses the operator <. The behaviour of < with NaNs does not satisfy the requirements of std::sort and the behaviour will be undefined if you try to sort a range that contains NaN (unless you provide a custom comparison function).

eerorika
  • 232,697
  • 12
  • 197
  • 326
  • 1
    more than one NaN? Given than `NaN < x` and `NaN > x` both return false I think sorting any number of NaNs is undefined? – Alan Birtles Feb 09 '20 at 18:36
  • @AlanBirtles the algorithm never uses `>`, so it doesn't matter how it behaves as far as `std::sort` is concerned. – eerorika Feb 09 '20 at 18:40
  • 1
    OK `NaN < x` and `x < NaN` both return false – Alan Birtles Feb 09 '20 at 18:44
  • ...from which you can deduce that the two are equivalent, because neither is less than the other. That's simply how the predicates for many STL algos work. You need a custom comparator. – Ulrich Eckhardt Feb 09 '20 at 18:51
  • @AlanBirtles On the other hand, there is always another value that also returns false for both: `x` itself. But I suppose that it is a problem for NaN to be equal to all other values. I've edited the anwer. – eerorika Feb 09 '20 at 18:51
  • Yep, that's the issue the result of `<` implies that `NaN` is equal to all other values which it isn't – Alan Birtles Feb 09 '20 at 18:52
  • @AlanBirtles well, by definition it **is** equal to all other values when compared with `<`. But being equal to more than one other value is presumably the problem. That is, the values that are equal to NaN are not equal to each other. – eerorika Feb 09 '20 at 18:54