justinmeiners / efficient-programming-with-components

Course notes for Alexander Stepanov's teachings on design and usage of C++ STL.
https://www.jmeiners.com/efficient-programming-with-components/
74 stars 6 forks source link

6: Fix min implementation #58

Closed DivineDominion closed 8 months ago

DivineDominion commented 8 months ago

Please double check, I fear I might miss something :)


I was looking at the .h file on the website:

template <typename T, typename Compare>
// Compare is StrictWeakOrdering on type T
inline
const T& min(const T& a, const T& b, Compare cmp) {
  if (cmp(b, a)) {
    return a;
  } else {
    return b; 
  }
}

so min(1, 2) would then eventually be evaluated as this (substituting all parameters):

const int min(1, 2, less) {
  if (less(2, 1)) {
    return 1;
  } else {
    return 2; 
  }
}

less(2,1) will be false, so the else branch executes, returning 2.

Read the rest of the script more closely, then. The fixed implementation further above is:

So let’s correct it, so we don’t swap unless necessary.

if (b < a) {
  return b;
} else {
  return a; 
}

It should definitely be b in the if branch.

This PR corrects the assembled template to match the corrected algorithm.

DivineDominion commented 8 months ago

https://www.youtube.com/watch?v=9S-Lh2J8_LU&t=2060s

2023-11-30 15-09-28 Arc - Efficient Programming with Components Lecture 4 Part 2@2x

Thanks to @oliverepper for digging up the timestamp

justinmeiners commented 8 months ago

Thanks! There must have been a mix up, because all the source material agrees with you.