cpp_weekly icon indicating copy to clipboard operation
cpp_weekly copied to clipboard

Ranges, algorithm: std::sort vs std::ranges::sort

Open monamimani opened this issue 2 years ago • 0 comments

Channel

C++Weekly

Topics

Topics: std::sort vs std::ranges::sort spaceship operator <=> concept totally ordered

I am proposing this episode because I got bitten hard on this. I couldn't figure out what I was doing wrong. I couldn't find any resource that talks about this change besides Stackoverflow questions. I am not a language expert, and I don't know much about the theoretical aspects of programming. I used to equate that if you want to sort a container, you need operator< defined. It worked well.

Then I learned about ranges and their algorithms. Every video, conference talk, and blog article that I saw says it is a drop-in replacement to the regular algorithm. They then proceed to sort a vector of int both ways. Voilà, CQFD...

But it is not. What I learned is ranges need to be totally ordered if you want to sort them with the default comparator. You would think concepts give better errors, but they don't ( but that is another issue). In short, you need operator<,<=,>,>=,== defined now even if they are not used ( you can't default them either), or use operator <=>, which defines them for you. but now, instead of just thinking about a < relationship, you need to think about all the other kind of relationship, which is more complex and UB prone ( from what I learn in a recent cppCon talk.

I think we need this PSA.

  • If you want to use the default comparator (std::ranges::less) define operator <=> ( and learn about all it complexities) and if <=> is not defaulted you need operator ==;
  • If you don't want/can't use std::less as the comparator. ( it suck because, this is the common usecase and it is not de default)
  • If it is a one time use, you can use a lambda

Length

5min

monamimani avatar Dec 28 '23 22:12 monamimani