C++ Sorting Pitfalls, UB & Type Conversion Explained
summary
Mixing long long and double in comparators leads to real undefined behavior: a custom comparator using a < b can produce non‑transitive results (example with four values that contradict order) because of implicit rounding when long long → double collapses distinct integers to the same double. std::sort, std::set and similar algorithms can crash, freeze, or return nonsense; compiler rounding is implementation‑defined. A working approach splits into three zones, does explicit rounding and bounds checks, uses hex constants for exact thresholds, and sends NaN values to the back.
AI-written summary · about
chapters (13)
- 0:00Introduction by Egor Suvorov
- 0:14Why comparing integers and floats is dangerous
- 0:26Sorting mixed types with std::sort
- 0:49Example of a broken comparator
- 1:28Implicit casts and precision loss
- 2:03Implementation-defined rounding behavior
- 2:20A safer approach to comparisons
- 2:39Three comparison zones, not two
- 3:06Issues with long long to double comparisons
- 3:36Fixing rounding and precision errors
- 4:00Improving constants with hex
- 4:15Handling NaN values safely
- 4:42Final tips and closing thoughts
related talks
53mC++ Features You Might Not Know
01h 30mSorting Algorithms: Speed Is Found In The Minds of People
01h 05mType Punning in C++17: Avoiding Pun-defined Behavior
01h 19mThis is C++: Uncompromised Performance, Undefined Behavior, & Move Semantics
05mThe dangers of C-style casts
57mAliasing: Risks, Opportunities and Techniques
29mintegral types
15mC++ WAT
