Working with numeric ranges is a frequent task in algorithm design and data processing. Determining the midpoint between two values appears straightforward, but naive implementations can introduce subtle issues - especially when dealing with large integers or pointer arithmetic.
Traditionally, the midpoint was computed using expressions like (a + b) / 2. While simple, this approach can lead to integer overflow when a and b are large. For pointer ranges, manual calculations were also required, which could reduce clarity and increase the chance of mistakes.
Since C++20, the std::midpoint function can be used for calculating the middle value between two inputs. It supports integers, floating-point numbers, and even pointers, while avoiding overflow in integral calculations.
#include <iostream>
#include <numeric>
int main() {
int m1 = std::midpoint(2147483641, 2147483647);
std::cout << m1 << std::endl; // 2147483644
float m2 = std::midpoint(15.1f, 20.3f);
std::cout << m2 << std::endl; // 17.7
int arr[] = {10, 20, 30, 40, 50};
int *m3 = std::midpoint(std::begin(arr), std::end(arr));
std::cout << *m3 << std::endl; // 30
return 0;
}
Leave a Comment
Cancel reply