# C++ Algorithm lexicographical_compare ()

C++ Algorithm lexicographical_compare () function is used to check if the first range [first1, last1) is lexicographically less than the second range [first2, last2).

Elements are compared using operator< for the first version or using the given binary comparison function comp for the second version.

Lexicographical comparison is an operation which has following properties:

• Comparison is done element by element in two ranges.
• The first mismatched element defines which range is lexicographically greater or less than the other.
• If one range is a prefix of another range, the shorter range is lexicographically less than the other.
• If two ranges contain equivalent elements and are of the same length, then the ranges are lexicographically equal.
• An empty range is lexicographically less than any other non-empty range.
• Two empty ranges are lexicographically equal.

## Parameter

first1: An input iterators pointing to the position of the first element in the first range to be compared.

last1: An input iterator pointing the position one past the last element in the first range to be compared.

first2: An input iterators pointing to the position of the first element in the second range to be compared.

last2: An input iterator pointing the position one past the last element in the second range to be compared.

comp: A user defined binary predicate function that accepts two arguments and returns true if the two arguments are in order and false otherwise. It follows the strict weak ordering to order the elements.

## Return value

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

## Complexity

Complexity is linear, performs at most 2*min (count1, count2) comparisons of comp. Where count1 = last1- first1 and count2 = last2 - first2.

## Exceptions

This function throws an exception if either element comparison or an iterator throws an exception.

Please note that invalid parameters cause an undefined behavior.

## Example 1

Let's see the simple example to demonstrate the use of lexicographical_compare():

Output:

`Comparing foo and bar lexicographically (foo`

## Example 2

Let's see another simple example:

Output:

```v1 is less than v2.
v1 is not less than v2.
```

## Example 3

Let's see another simple example:

Output:

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

## Example 4

Let's see a simple example:

Output:

```same length string compare:
x less than y
x not less than y

not same length string compare:
x less than y
x less than y
```

Next TopicC++ Algorithm

### Feedback

• Send your Feedback to feedback@javatpoint.com