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()
:
Use std::ranges::equal()
:
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.
An introduction to the eight main comparison algorithms in the C++ Standard Library