Comparison Algorithms

# Equal vs Lexicographical Compare

## When should I use lexicographical_compare() over equal()?

Use std::lexicographical_compare when you need to determine the relative ordering of two ranges, rather than just checking for equality. This function compares elements in a lexicographical (dictionary) order, which means it checks each element pair until it finds aÂ mismatch.

If it finds that an element in the first range is less than the corresponding element in the second range, it returns true. Here's anÂ example:

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

int main() {
std::vector<int> A{1, 2, 3};
std::vector<int> B{1, 2, 4};

if (std::lexicographical_compare(
A.begin(), A.end(), B.begin(), B.end())) {
std::cout << "A is less than B";
} else {
std::cout << "A is not less than B";
}
}
A is less than B

In contrast, std::ranges::equal() simply checks if two ranges have the same elements in the sameÂ order:

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

int main() {
std::vector<int> A{1, 2, 3};
std::vector<int> B{1, 2, 3};

if (std::ranges::equal(A, B)) {
std::cout << "Ranges are equal";
} else {
std::cout << "Ranges are not equal";
}
}
Ranges are equal

Use std::lexicographical_compare():

• When you need to sort or compare ranges based on order
• When implementing algorithms that depend on ordering, such as binary search or merge algorithms

Use std::ranges::equal():

• When you need to check if two ranges are exactly the same
• For equality checks where the order and presence of elements must match exactly

In summary, std::lexicographical_compare() is useful for determining if one range is less than another based on their order, while std::ranges::equal() is used to check for exact equality ofÂ ranges.

This Question is from the Lesson:

### Comparison Algorithms

An introduction to the eight main comparison algorithms in the C++ Standard Library

Answers to questions are automatically generated and may not have been reviewed.

This Question is from the Lesson:

### Comparison Algorithms

An introduction to the eight main comparison algorithms in the C++ Standard Library

Part of the course:

## Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

### This course includes:

• 124 Lessons
• 550+ Code Samples
• 96% Positive Reviews
• Regularly Updated
• Help and FAQ
Free, Unlimited Access

### Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.