Comparison Algorithms

Equal vs Lexicographical Compare

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

Abstract art representing computer programming

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.

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

A computer programmer
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:

  • 125 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.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved