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.

Comparison Algorithms

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

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

std::equal() vs std::is_permutation()
What is the difference between equal() and is_permutation()?
Custom Comparison for std::equal()
How do I customize the comparison behavior for equal()?
Handling Mismatch Results
How do I handle past-the-end iterators returned by mismatch()?
Applications of is_permutation()
What are some practical applications of is_permutation()?
Comparing Different Length Ranges
How do I compare two ranges of different lengths using mismatch()?
Understanding Identity Permutations
What are identity permutations and why are they important?
Comparing Floating Point Numbers
How do I compare ranges that contain floating-point numbers?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant