~/talk

C++ Sorting Pitfalls, UB & Type Conversion Explained

Talkat ACCU 2025 · 2025-04-01..04-04· [c-and-cpp]
links:none on file
slides:none on file

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

  1. 0:00Introduction by Egor Suvorov
  2. 0:14Why comparing integers and floats is dangerous
  3. 0:26Sorting mixed types with std::sort
  4. 0:49Example of a broken comparator
  5. 1:28Implicit casts and precision loss
  6. 2:03Implementation-defined rounding behavior
  7. 2:20A safer approach to comparisons
  8. 2:39Three comparison zones, not two
  9. 3:06Issues with long long to double comparisons
  10. 3:36Fixing rounding and precision errors
  11. 4:00Improving constants with hex
  12. 4:15Handling NaN values safely
  13. 4:42Final tips and closing thoughts
~/search
type to search 6,249 conferences, 138,987 speakers and 185,172 talks
~/help
cmdctrl k
search every conference, speaker and series
/
focus the filter search
h
home
c
conferences
s
speakers
e
series
t
light / dark — the status bar button does the same
?
this help
esc
close this, then clear every filter — or just the search, while you are typing in it

Ignored while you are typing. Pages without a filter rail have no search to focus.