algorithm_max_element
algorithm_max_element (최대 요소 찾기)
std::max_element는 대상 범위 [first, last)에서 가장 큰 요소를 찾아 반복자로 돌려줘요.
출처: cppreference
본문
std::max_element는 대상 범위 [first, last)에서 가장 큰 요소를 찾아요. <algorithm> 헤더에 정의되어 있어요.
template< class ForwardIt >
ForwardIt max_element( ForwardIt first, ForwardIt last );
template< class ForwardIt, class Compare >
ForwardIt max_element( ForwardIt first, ForwardIt last,
Compare comp );
- 1번 오버로드 — 요소를
operator<(즉std::less{})로 비교해요. - 2번 오버로드 — 요소를 비교 함수
comp로 비교해요. - 병렬 실행 정책을 받는 오버로드도 있어요.
반환값 (Return value)
범위의 가장 큰 요소를 가리키는 반복자예요. 범위가 비어 있으면 last를 돌려줘요.
복잡도 (Complexity)
N을 std::distance(first, last)라고 하면 정확히 max(N - 1, 0)번의 비교가 필요해요.
예제 (Example)
#include <algorithm>
#include <iostream>
#include <vector>
int main()
{
std::vector<int> v{3, 1, 4, 1, 5, 9, 2, 6};
auto result = std::max_element(v.begin(), v.end());
std::cout << "max element is " << *result << " at index "
<< std::distance(v.begin(), result) << '\n';
}
출력:
max element is 9 at index 5