std::midpoint
來自 cppreference.com
定義於標頭檔案 <numeric> |
||
template< class T > constexpr T midpoint( T a, T b ) noexcept; |
(1) | (C++20 起) |
template< class T > constexpr T* midpoint( T* a, T* b ); |
(2) | (C++20 起) |
計算整數、浮點數或指標 a 和 b 的中點。
1) 僅當
T
是除 bool 之外的算術型別時,此過載才參與過載決議。目錄 |
[編輯] 引數
a, b | - | 整數、浮點數或指標值 |
[編輯] 返回值
1) a 和 b 之和的一半。不會發生溢位。如果 a 和 b 具有整數型別且和為奇數,則結果向 a 四捨五入。如果 a 和 b 具有浮點型別,則最多發生一次不精確操作。
2) 如果 a 和 b 分別指向同一個陣列物件
x
的 x[i] 和 x[j](用於 指標算術),則返回指向 x[i + (j - i) / 2] 的指標(或等效地 x[std::midpoint(i, j)]),其中除法向零舍入。如果 a 和 b 不指向同一個陣列物件的元素,則行為未定義。[編輯] 異常
不丟擲異常。
[編輯] 注意
過載 (2) 在常見平臺上可以簡單地實現為 return a + (b - a) / 2;。然而,此實現不保證可移植,因為有些平臺可能建立元素數量大於 PTRDIFF_MAX 的陣列,且即使 b 和 a 都指向同一陣列中的元素,b - a 也可能導致未定義行為。
特性測試宏 | 值 | 標準 | 特性 |
---|---|---|---|
__cpp_lib_interpolate |
201902L |
(C++20) | std::lerp, std::midpoint |
[編輯] 示例
執行此程式碼
#include <cstdint> #include <iostream> #include <limits> #include <numeric> 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\n"; auto on_pointers = [](int i, int j) { char const* text = "0123456789"; char const* p = text + i; char const* q = text + j; std::cout << "std::midpoint('" << *p << "', '" << *q << "'): '" << *std::midpoint(p, q) << "'\n"; }; on_pointers(2, 4); on_pointers(2, 5); on_pointers(5, 2); on_pointers(2, 6); }
輸出
a: 4294967295 b: 4294967293 Incorrect (overflow and wrapping): 2147483646 Correct: 4294967294 std::midpoint('2', '4'): '3' std::midpoint('2', '5'): '3' std::midpoint('5', '2'): '4' std::midpoint('2', '6'): '4'
[編輯] 參考
- C++23 標準 (ISO/IEC 14882:2024)
- 27.10.16 中點 [numeric.ops.midpoint]
- C++20 標準 (ISO/IEC 14882:2020)
- 25.10.15 中點 [numeric.ops.midpoint]
[編輯] 參閱
(C++20) |
線性插值函式 (function) |