Updated:

1 minute read

개요

  • 정수, 부동 소수점 혹은 포인터 a와 b의 중간점을 반환
  • 오버로드가 발생하지 않음
    • (a+b)/2 대신 a+(b-a)/2를 사용해도 오버로드가 발생하지 않음
  • a와 b가 정수 유형일 경우 합이 홀수인 경우 a쪽으로 반올림
  • a와 b가 부동 소수점일 경우 합이 홀수인 경우 최대 하나의 부정확한 연산 발생
  • a와 b가 포인터(a = x[i], b = x[j])일 경우 x[midpoint(i, j)]에 대한 포인터 반환


예제

  • 코드
     #include <algorithm>
     #include <iostream>
     #include <limits>
     #include <numeric>
     #include <vector>
        
     using namespace std;
        
     int main() {
     	auto func = [](auto x, auto y) {
     		if constexpr (is_pointer<decltype(x)>::value) {
     			cout << "x : " << *x << ", y : " << *y << endl;
     			cout << "midpoint : " << *midpoint(x, y) << endl << endl;
     		} else {
     			cout << "x : " << x << ", y : " << y << endl;
     			cout << "midpoint : " << midpoint(x, y) << endl << endl;
     		}
     	};
        
     	func(1, 3);
     	func(1, 6);
     	func(numeric_limits<int>::max() - 2, numeric_limits<int>::max());
        
     	vector<int> v = {1, 2, 3};
     	func(v.data(), v.data() + v.size() - 1);
        
     	return 0;
     }
    
  • 실행 결과
     x : 1, y : 3
     midpoint : 2
        
     x : 1, y : 6
     midpoint : 3
        
     x : 2147483645, y : 2147483647
     midpoint : 2147483646
        
     x : 1, y : 3
     midpoint : 2