VOOZH about

URL: https://www.geeksforgeeks.org/cpp/lexicographical_compare-in-cpp/

⇱ lexicographical_compare in C++ - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

lexicographical_compare in C++

Last Updated : 11 Mar, 2024

C++ STL offer many utilities to solve basic common life problems. Comparing values are always necessary, but sometimes we need to compare the strings also. Therefore, this article aims at explaining about "lexicographical_compare()" that allows to compare strings. This function is defined in "algorithm" header. It has two implementations. Syntax 1 : lexicographical_compare(iter1 beg1, iter1 end1, iter2 beg2, iter2 end2)

Template:
template 
 bool lexicographical_compare(iter1 beg1, iter1 end1, iter2 beg2, iter2 end2)
Parameters : 
beg1 :  Input iterator to initial position of first sequence.
end1 :  Input iterator to final position of first sequence.

beg2 :  Input iterator to initial position of second sequence.
end2 :  Input iterator to final position of second sequence.

Return value : 
Returns a boolean true, if range1 is strictly lexicographically 
smaller than range2 else returns a false.

Time Complexity: O(N)

Space Complexity: O(1)

Output:

geeksforgeeks is lexicographically less than gfg


Syntax 2 : lexicographical_compare(iter1 beg1, iter1 end1, iter2 beg2, iter2 end2, Compare comp)

Template:
template 
 bool lexicographical_compare(iter1 beg1, iter1 end1, iter2 beg2, iter2 end2)
Parameters : 
beg1 :  Input iterator to initial position of first sequence.
end1 :  Input iterator to final position of first sequence.

beg2 :  Input iterator to initial position of second sequence.
end2 :  Input iterator to final position of second sequence.

comp : The comparator function that returns a boolean
true/false of the each elements compared. This function 
accepts two arguments. This can be function pointer or 
function object and cannot change values.

Return value : 
Returns a boolean true, if range1 is strictly lexicographically smaller 
than range2 else returns a false.

Time Complexity: O(N)

Space Complexity: O(1)

Output:

geeksforgeeks is not lexicographically less than Gfg
geeksforgeeks is lexicographically less than Gfg( case-insensitive )


Possible application : Comparing strings can be generally used in dictionary, where we need to place words in lexicographical order. Example of this can be to find the word which occurs 1st in dictionary among given set of words. 

Time Complexity: O(N)

Space Complexity: O(1)

Output:

The smallest string is : abacus


Comment