ranges::fold_right_last

ranges::fold_right_last (마지막 요소 기반 오른쪽 폴드)

초기값을 따로 두지 않고, 범위의 마지막 요소를 초기값으로 삼아 오른쪽 폴드를 수행하는 ranges 알고리즘이에요. <algorithm> 헤더, C++23부터.

출처: cppreference

본문

std::ranges::fold_right_last[first, last)의 마지막 요소를 누적 초기값으로 두고, 앞쪽 요소를 오른쪽부터 이진 연산 f로 누적해요.

namespace std::ranges {
template< std::bidirectional_iterator I, std::sentinel_for<I> S,
          std::indirectly_binary_right_foldable<std::iter_value_t<I>, I> F >
constexpr auto fold_right_last( I first, S last, F f );
}
  • 반환 타입은 std::optional(요소 타입). 범위가 비면 std::nullopt.
  • fold_right가 명시적 init을 요구하는 반면, fold_right_last는 마지막 요소를 초기값으로 써요.
std::vector<int> v{1, 2, 3};
auto r = std::ranges::fold_right_last(v, [](int a, int b){ return a - b; });
// 1 - (2 - 3) = 2

오른쪽 폴드를 비어 있는 경우와 함께 다루고 싶을 때 유용해요.

더 알아보기 (Learn more)

cppreference