ranges::fold_left_first

ranges::fold_left_first (첫 요소 기반 왼쪽 폴드)

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

출처: cppreference

본문

std::ranges::fold_left_first[first, last)의 첫 요소를 누적 초기값으로 두고, 나머지 요소를 왼쪽부터 이진 연산 f로 누적해요.

namespace std::ranges {
template< std::input_iterator I, std::sentinel_for<I> S,
          std::indirectly_binary_left_foldable<std::iter_value_t<I>, I> F >
constexpr auto fold_left_first( I first, S last, F f );
}
  • 반환 타입은 std::optional(요소 타입). 범위가 비어 있으면 std::nullopt.
  • fold_left가 명시적 init을 요구하는 반면, fold_left_first는 첫 요소를 초기값으로 써요.
std::vector<int> v{5, 6, 2};
auto mx = std::ranges::fold_left_first(v,
                 [](int a, int b){ return std::max(a, b); });
// 6 (첫 요소 5에서 시작해 max 누적)

중립 초기값(예: 합의 0)이 없거나, 비어 있는 경우를 자연스럽게 다루고 싶을 때 유용해요.

더 알아보기 (Learn more)

cppreference