lexicographical_compare function template — Compares ranges for less-than
template<typename InIter1, typename InIter2> bool lexicographical_compare(InIter1 first1, InIter1 last1, InIter2 first2, InIter2 last2); template<typename InIter1, typename InIter2, typename Compare> bool lexicographical_compare(InIter1 first1, InIter1 last1, InIter2 first2, InIter2 last2, Compare comp);
The lexicographical_compare
function template returns true
if
the sequence [first1
, last1
) is less than the sequence [first2
, last2
). If the sequences have the same
length and contents, the return value is false
. If the second sequence is a prefix
of the first, true
is returned.
(The use of "lexicographical" emphasizes that the ranges are
compared element-wise, like letters in words.)
The first form uses the <
operator to compare elements. The
second form calls comp(*iter1
,
*iter2)
.
Let length1
= last1
- first1
, length2
= last2
- first2
, and minlength
= min(length1
, length2
).
The lexicographical_compare
function template returns true
if
either of the following conditions is true:
There is an n
in [0,
minlength
) such that
*(first1
+ m
) == *(first2
+ m
) for all m
in [0, n
- 1), and *(first1
+
n
) < *(first2
+ n
).
*(first1
+ n
) == *(first2
+ n
) for all n
in [0, length2
) and length2
< length1
.
Complexity is linear: at most, minlength
comparisons are
performed.
#include <algorithm> #include <iostream> #include <ostream> int main( ) { using namespace std; int a[] = { 1, 10, 3, 42 }; int b[] = { 1, 10, 42, 3 }; int c[] = { 1, 10 }; cout << boolalpha; cout << lexicographical_compare(a, a+4, b, b+4); // true cout << lexicographical_compare(a, a+4, c, c+2); // false cout << lexicographical_compare(a, a+4, a, a+4); // false cout << lexicographical_compare(c, c+2, b, b+4); // true }