On this page
std::lexicographical_compare_three_way
Defined in header <algorithm> |
||
---|---|---|
|
(1) | (since C++20) |
|
(2) | (since C++20) |
Lexicographically compares two ranges [
first1
,
last1
)
and [
first2
,
last2
)
using three-way comparison and produces a result of the strongest applicable comparison category type.
1) Returns the order between the first non-equivalent pair of elements according to
comp
in both ranges if any, otherwise (if one ranges is equivalent to the prefix of another according to comp
), returns the order between the length of both ranges.
2) Equivalent to:
return std::lexicographical_compare_three_way(
first1, last1, first2, last2, std::compare_three_way());
Parameters
first1, last1 | - | the first range of elements to examine |
first2, last2 | - | the second range of elements to examine |
comp | - | a function object type. The program is ill-formed if its return type is not one of the three comparison category types (std::strong_ordering , std::weak_ordering , or std::partial_ordering ). |
Type requirements | ||
-InputIt1, InputIt2 must meet the requirements of LegacyInputIterator. |
Return value
The value of a comparison category type specified above.
Complexity
At most N applications of comp
, where N is the smaller of length of both ranges.
Possible implementation
|
Example
#include <algorithm>
#include <cctype>
#include <compare>
#include <iomanip>
#include <iostream>
#include <string_view>
#include <utility>
using namespace std::literals;
void show_result(std::string_view s1, std::string_view s2, std::strong_ordering o)
{
std::cout << std::quoted(s1) << " is ";
std::is_lt(o) ? std::cout << "less than ":
std::is_gt(o) ? std::cout << "greater than ":
std::cout << "equal to ";
std::cout << std::quoted(s2) << '\n';
}
std::strong_ordering cmp_icase(unsigned char x, unsigned char y)
{
return std::toupper(x) <=> std::toupper(y);
};
int main()
{
for (const auto& [s1, s2] :
{
std::pair{"one"sv, "ONE"sv}, {"two"sv, "four"sv}, {"three"sv, "two"sv}
})
{
const auto res = std::lexicographical_compare_three_way(
s1.cbegin(), s1.cend(), s2.cbegin(), s2.cend(), cmp_icase);
show_result(s1, s2, res);
}
}
Output:
"one" is equal to "ONE"
"two" is greater than "four"
"three" is less than "two"
Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
DR | Applied to | Behavior as published | Correct behavior |
---|---|---|---|
LWG 3410 | C++20 | extraneous comparisons between iterators were required | such requirement removed |
See also
returns true if one range is lexicographically less than another (function template) |
|
(C++20)
|
function object implementing x <=> y (class) |
(C++20)
|
returns true if one range is lexicographically less than another(niebloid) |
© cppreference.com
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.
https://en.cppreference.com/w/cpp/algorithm/lexicographical_compare_three_way