Namespaces
Variants

std:: lexicographical_compare

From cppreference.net
Algorithm library
Constrained algorithms and algorithms on ranges (C++20)
Constrained algorithms, e.g. ranges::copy , ranges::sort , ...
Execution policies (C++17)
Non-modifying sequence operations
Batch operations
(C++17)
Search operations
Modifying sequence operations
Copy operations
(C++11)
(C++11)
Swap operations
Transformation operations
Generation operations
Removing operations
Order-changing operations
(until C++17) (C++11)
(C++20) (C++20)
Sampling operations
(C++17)

Sorting and related operations
Partitioning operations
Sorting operations
Binary search operations
(on partitioned ranges)
Set operations (on sorted ranges)
Merge operations (on sorted ranges)
Heap operations
Minimum/maximum operations
Lexicographical comparison operations
lexicographical_compare
Permutation operations
C library
Numeric operations
Operations on uninitialized memory
헤더 파일에 정의됨 <algorithm>
template < class InputIt1, class InputIt2 >

bool lexicographical_compare ( InputIt1 first1, InputIt1 last1,

InputIt2 first2, InputIt2 last2 ) ;
(1) (C++20부터 constexpr)
template < class ExecutionPolicy,

class ForwardIt1, class ForwardIt2 >
bool lexicographical_compare ( ExecutionPolicy && policy,
ForwardIt1 first1, ForwardIt1 last1,

ForwardIt2 first2, ForwardIt2 last2 ) ;
(2) (C++17부터)
template < class InputIt1, class InputIt2, class Compare >

bool lexicographical_compare ( InputIt1 first1, InputIt1 last1,
InputIt2 first2, InputIt2 last2,

Compare comp ) ;
(3) (C++20부터 constexpr)
template < class ExecutionPolicy,

class ForwardIt1, class ForwardIt2, class Compare >
bool lexicographical_compare ( ExecutionPolicy && policy,
ForwardIt1 first1, ForwardIt1 last1,
ForwardIt2 first2, ForwardIt2 last2,

Compare comp ) ;
(4) (C++17부터)

첫 번째 범위 [ first1 , last1 ) 가 두 번째 범위 [ first2 , last2 ) 보다 사전순으로 작은지 확인합니다.

1) 요소들은 operator < 를 사용하여 비교됩니다.
3) 요소들은 주어진 이항 비교 함수 comp 를 사용하여 비교됩니다.
2,4) (1,3) 와 동일하지만 policy 에 따라 실행됩니다. 이러한 오버로드는 다음의 모든 조건이 충족될 때만 오버로드 해결에 참여합니다:

std:: is_execution_policy_v < std:: decay_t < ExecutionPolicy >> true 인 경우.

(C++20 이전)

std:: is_execution_policy_v < std:: remove_cvref_t < ExecutionPolicy >> true 인 경우.

(C++20 이후)

사전식 비교(lexicographical comparison)는 다음과 같은 속성을 가진 연산입니다:

  • 두 범위는 요소별로 비교됩니다.
  • 첫 번째 불일치하는 요소가 어떤 범위가 사전식으로 less 또는 greater 인지를 결정합니다.
  • 한 범위가 다른 범위의 접두사인 경우, 더 짧은 범위가 사전식으로 less 입니다.
  • 두 범위가 동등한 요소를 가지고 길이가 같은 경우, 범위는 사전식으로 equal 입니다.
  • 빈 범위는 사전식으로 모든 비어 있지 않은 범위보다 less 입니다.
  • 두 빈 범위는 사전식으로 equal 입니다.

목차

매개변수

first1, last1 - 검사할 첫 번째 원소들의 범위 를 정의하는 반복자 쌍
first2, last2 - 검사할 두 번째 원소들의 범위 를 정의하는 반복자 쌍
policy - 사용할 실행 정책
comp - 비교 함수 객체(즉, Compare 요구 사항을 만족하는 객체)로 첫 번째 인수가 두 번째 인수보다 작으면 true 를 반환함.

비교 함수의 시그니처는 다음에 부합해야 함:

bool cmp ( const Type1 & a, const Type2 & b ) ;

시그니처가 반드시 const & 를 가질 필요는 없지만, 함수는 전달된 객체를 수정해서는 안 되며 값 범주 에 관계없이 (가능한 const인) Type1 Type2 타입의 모든 값을 수용할 수 있어야 함(따라서 Type1 & 는 허용되지 않으며, Type1 Type1 에 대해 이동이 복사와 동등하지 않는 한 허용되지 않음 (C++11부터) ).
Type1 Type2 타입은 InputIt1 InputIt2 타입의 객체가 역참조된 후 Type1 Type2 양쪽으로 암시적으로 변환 가능해야 함.

타입 요구 사항
-
InputIt1, InputIt2 LegacyInputIterator 요구 사항을 충족해야 함.
-
ForwardIt1, ForwardIt2 LegacyForwardIterator 요구 사항을 충족해야 함.
-
Compare Compare 요구 사항을 충족해야 함.

반환값

true 첫 번째 범위가 두 번째 범위보다 사전순으로 작은 경우, 그렇지 않으면 false .

복잡도

N 1 std:: distance ( first1, last1 ) 로, N 2 std:: distance ( first2, last2 ) 로 정의할 때:

1,2) 최대 2min( 1 ,N 2 ) 번의 비교를 operator < 를 사용하여 수행합니다.
3,4) 최대 2min(N 1 ,N 2 ) 번의 비교 함수 comp 적용.

예외

ExecutionPolicy 라는 템플릿 매개변수를 사용하는 오버로드는 다음과 같이 오류를 보고합니다:

  • 알고리즘의 일부로 호출된 함수 실행 중 예외가 발생하고 ExecutionPolicy 표준 정책 중 하나인 경우, std::terminate 가 호출됩니다. 다른 ExecutionPolicy 의 경우 동작은 구현에 따라 정의됩니다.
  • 알고리즘이 메모리 할당에 실패할 경우, std::bad_alloc 이 throw됩니다.

가능한 구현

lexicographical_compare (1)
template<class InputIt1, class InputIt2>
bool lexicographical_compare(InputIt1 first1, InputIt1 last1,
                             InputIt2 first2, InputIt2 last2)
{
    for (; (first1 != last1) && (first2 != last2); ++first1, (void) ++first2)
    {
        if (*first1 < *first2)
            return true;
        if (*first2 < *first1)
            return false;
    }
    return (first1 == last1) && (first2 != last2);
}
lexicographical_compare (3)
template<class InputIt1, class InputIt2, class Compare>
bool lexicographical_compare(InputIt1 first1, InputIt1 last1,
                             InputIt2 first2, InputIt2 last2, Compare comp)
{
    for (; (first1 != last1) && (first2 != last2); ++first1, (void) ++first2)
    {
        if (comp(*first1, *first2))
            return true;
        if (comp(*first2, *first1))
            return false;
    }
    return (first1 == last1) && (first2 != last2);
}

예제

#include <algorithm>
#include <iostream>
#include <random>
#include <vector>
void print(const std::vector<char>& v, auto suffix)
{
    for (char c : v)
        std::cout << c << ' ';
    std::cout << suffix;
}
int main()
{
    std::vector<char> v1{'a', 'b', 'c', 'd'};
    std::vector<char> v2{'a', 'b', 'c', 'd'};
    for (std::mt19937 g{std::random_device{}()};
         !std::lexicographical_compare(v1.begin(), v1.end(),
                                       v2.begin(), v2.end());)
    {
        print(v1, ">= ");
        print(v2, '\n');
        std::shuffle(v1.begin(), v1.end(), g);
        std::shuffle(v2.begin(), v2.end(), g);
    }
    print(v1, "<  ");
    print(v2, '\n');
}

가능한 출력:

a b c d >= a b c d 
d a b c >= c b d a 
b d a c >= a d c b 
a c d b <  c d a b

결함 보고서

다음의 동작 변경 결함 보고서들은 이전에 발표된 C++ 표준에 소급 적용되었습니다.

DR 적용 대상 게시된 동작 올바른 동작
LWG 142 C++98 최대 min(N 1 ,N 2 ) 비교가 허용되었으나, 이는
불가능함 (동등성은 2회 비교로 결정됨)
제한을 두 배로 증가
LWG 1205 C++98 빈 범위를 포함하는 사전식 비교 결과가 불명확했음 명확하게 규정

참고 항목

두 요소 집합이 동일한지 결정합니다
(함수 템플릿)
3-way 비교를 사용하여 두 범위를 비교합니다
(함수 템플릿)
한 범위가 다른 범위보다 사전순으로 작으면 true 를 반환합니다
(알고리즘 함수 객체)