algorithm_lexicographical_compare_three_way

algorithm_lexicographical_compare_three_way (3방향 사전식 비교)

std::lexicographical_compare_three_way는 두 대상 범위를 3방향 비교(three-way comparison)로 사전식 순서를 검사해요. lexicographical_compare의 3방향 버전이에요.

출처: cppreference

본문

std::lexicographical_compare_three_way는 두 대상 범위 [first1, last1)[first2, last2)를 3방향 비교를 사용해 사전식 순서를 검사해요. <algorithm> 헤더에 정의되어 있어요. C++20부터 사용 가능해요.

template< class InputIt1, class InputIt2, class Cmp >
constexpr auto lexicographical_compare_three_way
    ( InputIt1 first1, InputIt1 last1, InputIt2 first2, InputIt2 last2,
      Cmp comp ) -> decltype(comp(*first1, *first2));

template< class InputIt1, class InputIt2 >
constexpr auto lexicographical_compare_three_way
    ( InputIt1 first1, InputIt1 last1, InputIt2 first2, InputIt2 last2 );
  • 1번 오버로드 — 요소를 비교 함수 comp로 비교해요.
  • 2번 오버로드 — 요소를 std::compare_three_way()로 비교해요.

사전식 비교는 첫 번째 서로 다른 요소 쌍을 찾아 3방향 비교 결과를 돌려주고, 일치하는 요소가 없으면(한 범위가 다른 범위의 접두어이면) 각 범위의 길이를 비교해요.

반환값 (Return value)

3방향 비교의 결과(std::strong_ordering 등)예요. 첫 번째 범위가 작으면 less, 크면 greater, 같으면 equal이에요.

복잡도 (Complexity)

범위 요소 수에 선형이에요.

예제 (Example)

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

int main()
{
    std::vector<int> a{1, 2, 3};
    std::vector<int> b{1, 2, 4};
    auto r = std::lexicographical_compare_three_way(a.begin(), a.end(),
                                                    b.begin(), b.end());
    std::cout << (r < 0 ? "less" : r > 0 ? "greater" : "equal") << '\n';
}

출력:

less

더 알아보기 (Learn more)

cppreference