lexicographical_compare


Lexicographically compare two sequences.

Use a pair of iterators i and j to traverse two sequences, starting at first1 and first2 , respectively. While traversing the sequences, if * i is less than * j , immediately return true . Similarly, if * j < * i , immediately return false . If the end of the first sequence is reached before the end of the second sequence, return true ; otherwise, return false . The first version uses operator< to perform the comparison, whereas the second version uses compare .

Library

Standards<ToolKit>

Declaration


#include <algorithm>

template< class InputIterator1, class InputIterator2 >
bool lexicographical_compare
  (
  InputIterator1 first1,
  InputIterator1 last1,
  InputIterator2 first2,
  InputIterator2 last2
  );

template< class InputIterator1, class InputIterator2, class Compare >
bool lexicographical_compare
  (
  InputIterator1 first1,
  InputIterator1 last1,
  InputIterator2 first2,
  InputIterator2 last2,
  Compare compare
  );
  

Complexity

Time complexity is linear, as at most the lessor of ( last1 - first1 ) and ( last2 - first2 ) comparisons are performed. Space complexity is constant.

Example <ospace/osstd/examples/lexcmp1.cpp>
#include <iostream>
#include <algorithm>

const unsigned size = 6;
char n1[ size ] = "shoe";
char n2[ size ] = "shine";

void
main()
  {
  bool before = lexicographical_compare( n1, n1 + size, n2, n2 + size );

  if( before )
    cout << n1 << " is before " << n2 << "\n";
  else
    cout << n2 << " is before " << n1 << "\n";
  }

shine is before shoe
Example <ospace/osstd/examples/lexcmp2.cpp>
#include <iostream>
#include <algorithm>
#include <functional>

const unsigned size = 6;
char n1[ size ] = "shoe";
char n2[ size ] = "shine";

void
main()
  {
  bool before = lexicographical_compare
    (
    n1,
    n1 + size,
    n2,
    n2 + size,
    greater< char >()
    );

  if( before )
    cout << n1 << " is after " << n2 << "\n";
  else
    cout << n2 << " is after " << n1 << "\n";
  }

shoe is after shine

Copyright©1994-2026 Recursion Software LLC
All Rights Reserved - For use by licensed users only.