Search code examples
c++sortingc++11stdrcpparmadillo

How does std::sort handle NaN values?


I was using the sort function in the Armadillo library but it kept firing "NaN errors" which were nonexistent when I checked manually. I've switched to the std::sort function and it worked!

So I'm wondering: how does the std::sort function treat NaNs?


Solution

  • 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).