algorithm_is_sorted

algorithm_is_sorted (정렬 여부 검사)

std::is_sorted는 소스 범위 [first, last)의 모든 요소가 정렬되어 있는지 검사해요.

출처: cppreference

본문

std::is_sorted는 소스 범위 [first, last)의 모든 요소가 정렬되어 있는지 검사해요. <algorithm> 헤더에 정의되어 있어요.

template< class ForwardIt >
bool is_sorted( ForwardIt first, ForwardIt last );

template< class ForwardIt, class Compare >
bool is_sorted( ForwardIt first, ForwardIt last, Compare comp );
  • 1번 오버로드 — 모든 요소가 operator<(즉 std::less{})를 기준으로 정렬되어 있는지 검사해요.
  • 2번 오버로드 — 모든 요소가 비교 함수 comp를 기준으로 정렬되어 있는지 검사해요.
  • 병렬 실행 정책을 받는 오버로드도 있어요.

반환값 (Return value)

범위가 정렬되어 있으면 true, 아니면 false예요.

복잡도 (Complexity)

Nstd::distance(first, last)라고 하면 최대 N - 1번의 비교가 필요해요.

예제 (Example)

#include <algorithm>
#include <iostream>
#include <vector>

int main()
{
    std::vector<int> v{1, 2, 3, 4, 5};
    std::cout << std::boolalpha << std::is_sorted(v.begin(), v.end()) << '\n';
    std::vector<int> v2{1, 3, 2, 4, 5};
    std::cout << std::boolalpha << std::is_sorted(v2.begin(), v2.end()) << '\n';
}

출력:

true
false

더 알아보기 (Learn more)

cppreference