std::lexicographical_compare

Header: <algorithm>

Checks if the first range [first1,last1) is lexicographically less than the second range [first2,last2).

# Declarations

template< class InputIt1, class InputIt2 >
bool lexicographical_compare( InputIt1 first1, InputIt1 last1,
InputIt2 first2, InputIt2 last2 );

(constexpr since C++20)

template< class ExecutionPolicy,
class ForwardIt1, class ForwardIt2 >
bool lexicographical_compare( ExecutionPolicy&& policy,
ForwardIt1 first1, ForwardIt1 last1,
ForwardIt2 first2, ForwardIt2 last2 );

(since C++17)

template< class InputIt1, class InputIt2, class Compare >
bool lexicographical_compare( InputIt1 first1, InputIt1 last1,
InputIt2 first2, InputIt2 last2,
Compare comp );

(constexpr since C++20)

template< class ExecutionPolicy,
class ForwardIt1, class ForwardIt2, class Compare >
bool lexicographical_compare( ExecutionPolicy&& policy,
ForwardIt1 first1, ForwardIt1 last1,
ForwardIt2 first2, ForwardIt2 last2,
Compare comp );

(since C++17)

# Parameters

# Return value

true if the first range is lexicographically less than the second, otherwise false.

# Example

#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');
}

# Defect reports

DRApplied toBehavior as publishedCorrect behavior
LWG 142C++98at most (\scriptsize \min(N_1,N_2))min(N1,N2) comparisons were allowed, but thatis not possible (equivalence is determined by 2 comparisons)doubled the limit
LWG 1205C++98the results of lexicographical comparisons involving empty ranges were unclearmade clear

# See also