Library: Algorithms
Function
Algorithm that returns true if one sequence compares lexicographically less than another, false otherwise
#include <algorithm> namespace std { template <class InputIterator1, class InputIterator2> bool lexicographical_compare(InputIterator1 start1, InputIterator1 finish1, InputIterator2 start2, InputIterator2 finish2); template <class InputIterator1, class InputIterator2, class Compare> bool lexicographical_compare(InputIterator1 start1, InputIterator1 finish1, InputIterator2 start2, InputIterator2 finish2, Compare comp); }
The lexicographical_compare() functions compare each element in the range [start1, finish1) to the corresponding element in the range [start2, finish2) using iterators i and j.
The first version of the algorithm uses operator<() as the default comparison operator. It immediately returns true if it encounters any pair in which *i is less than *j, and immediately returns false if *j is less than *i. If the algorithm reaches the end of the first sequence before reaching the end of the second sequence, it also returns true.
The second version of the function takes an argument comp that defines a comparison function that is used in place of the default operator<().
The lexicographical_compare() functions can be used with all the data types included in the standard library.
lexicographical_compare() performs at most min((finish1 - start1), (finish2 - start2)) applications of the comparison function.
// // lex_comp.cpp // #include <algorithm> #include <functional> #include <iostream> #include <vector> int main() { typedef std::vector<int, std::allocator<int> > Vector; const Vector::value_type d1[] = { 1, 3, 5, 32, 64 }; const Vector::value_type d2[] = { 1, 3, 2, 43, 56 }; // Create vectors. Vector v1 (d1 + 0, d1 + sizeof d1 / sizeof *d1); Vector v2 (d2 + 0, d2 + sizeof d1 / sizeof *d2); // Is v1 less than v2 (I think not). bool b1 = std::lexicographical_compare (v1.begin (), v1.end (), v2.begin (), v2.end ()); // Is v2 less than v1 (yup, sure is). bool b2 = std::lexicographical_compare(v2.begin (), v2.end (), v1.begin (), v1.end (), std::less<int>()); std::cout << std::boolalpha << b1 << " " << b2 << std::endl; return 0; } Program Output:
false true
ISO/IEC 14882:1998 -- International Standard for Information Systems -- Programming Language C++, Section 25.3.8