lexicographical_compare

C++ Library  
 

Header

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

Lexicographically compare two sequences. The lexicographical comparison is a dictionary comparison in which words are compared for ordering. Compares two sequences [first1, last1) and [first2, last2) as follows: traverses the sequences, comparing corresponding pairs of elements e1 and e2: if e1 < e2, then return true. If e2 < e1, then return false, otherwise continue to the next corresponding pair of elements. If the first sequence gets exhausted but the second is not, return true, otherwise return false.

The non-predicate version uses operator== for comparison.

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

Lexicographically compare two sequences. The lexicographical comparison is a dictionary comparison in which words are compared for ordering. Compares two sequences [first1, last1) and [first2, last2) as follows: traverses the sequences, comparing corresponding pairs of elements e1 and e2: if e1 < e2, then return true. If e2 < e1, then return false, otherwise continue to the next corresponding pair of elements. If the first sequence gets exhausted but the second is not, return true, otherwise return false.

The predicate version uses the predicate function pr for comparison.


Samples

#pragma warning (disable:4786)

#include <algorithm>
#include <iostream>
#include <string>
#include <cstring>
#include <functional>

int main()
{
	std::string s1("Shaun"), s2("Shawn") ;
	char *s3 = "Sammy" ;
	char *s4 = "Sam" ;
	int s3Len = strlen(s3) ;
	int s4Len = strlen(s4) ;
	bool result ;
	
	//non-predicate version of lexicographical_compare
	result = std::lexicographical_compare(s1.begin(), s1.end(), s2.begin(), s2.end()) ;
	
	std::cout << "s1 = " << s1 << std::endl ;
	std::cout << "s2 = " << s1 << std::endl ;
	std::cout << "using non-predicate version of lexicographical_compare" << std::endl ;
	if (result)
		std::cout << "s1 < s2" << std::endl ;
	else
		std::cout << "s1 >= s2" << std::endl ;

	//predicate version of lexicographical_compare
	result = std::lexicographical_compare(s3, s3+s3Len, s4, s4+s4Len, std::less<char>()) ;
	
	std::cout << "\n\ns3 = " << s3 << std::endl ;
	std::cout << "s4 = " << s4 << std::endl ;
	std::cout << "using non-predicate version of lexicographical_compare" << std::endl ;
	if (result)
		std::cout << "s3 < s4" << std::endl ;
	else
		std::cout << "s3 >= s4" << std::endl ;
	return 0 ;
}

Program Output

s1 = Shaun
s2 = Shaun
using non-predicate version of lexicographical_compare
s1 < s2


s3 = Sammy
s4 = Sam
using non-predicate version of lexicographical_compare
s3 >= s4

© 1997 Microsoft Corporation. All rights reserved. Terms of Use.