std::midpoint
From cppreference.com
Defined in header <numeric>
|
||
template< class T > constexpr T midpoint(T a, T b) noexcept; |
(1) | (since C++20) |
template< class T > constexpr T* midpoint(T* a, T* b); |
(2) | (since C++20) |
Computes the midpoint of the integers, floating-points, or pointers a
and b
.
1) This overload only participates in overload resolution if
T
is an arithmetic type other than bool
.2) This overload only participates in overload resolution if
T
ia an object type. Use of this overload is ill-formed if T
is an incomplete type.Parameters
a, b | - | integers, floating-points, or pointer values |
Return value
1) Half the sum of
a
and b
. No overflow occurs. If a
and b
have integer type and the sum is odd, the result is rounded towards a
. If a
and b
have floating-point type, at most one inexact operation occurs.2) If
a
and b
point to, respectively, x[i]
and x[j]
of the same array object x
(for the purpose of pointer arithmetic), returns a pointer to x[i+(j-i)/2]
where the division rounds towards zero. If a
and b
do not point to elements of the same array object, the behavior is undefined.Exceptions
Throws no exceptions.
Example
Run this code
#include <cstdint> #include <limits> #include <numeric> #include <iostream> int main() { std::uint32_t a = std::numeric_limits<std::uint32_t>::max(); std::uint32_t b = std::numeric_limits<std::uint32_t>::max() - 2; std::cout << "a: " << a << '\n' << "b: " << b << '\n' << "Incorrect (overflow and wrapping): " << (a + b) / 2 << '\n' << "Correct: " << std::midpoint(a, b) << '\n'; }
Output:
a: 4294967295 b: 4294967293 Incorrect (overflow and wrapping): 2147483646 Correct: 4294967294