lefticus / cpp_weekly

The official C++ Weekly Repository. Code samples and notes of future / past episodes will land here at various times. PR's will be accepted in some cases.
The Unlicense
663 stars 24 forks source link

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

Open monamimani opened 6 months ago

monamimani commented 6 months ago

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.

Length

5min