C++ std::lexicographical_compare with std::array














































C++ std::lexicographical_compare with std::array



 This article is about the lexicographical_compare() algorithm function with std::array
 container. It is an STL algorithm in <algorithm> header file.
 It is used for comparing two words according to the dictionary. It specifies which word will
 come first and which will come after that. It sequentially compares each character in the
 same position of both the strings until one element is not equal to the other. If both of
 them compares equally then the one which is shorter in length comes before the other.
 
 lexicographical_compare() can take two forms:
(1) template <class InputIterator1, class InputIterator2> bool lexicographical_compare (InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2); (2) template <class InputIterator1, class InputIterator2, class Compare> bool lexicographical_compare (InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, Compare comp); two elements are compared equal using operator '<' in definition (1) or by using a comp function in definition (2). Return value: True if the first range is lexicographically less than the second else false. Here the first definition is discussed.

 Program:
 Enter a few names and rearrange them according to the English Dictionary.

#include<iostream>
#include<string.h> //for strlen
#include<algorithm> // for lexicographical_compare
#include<cstdio> // for gets

using namespace std;

int main()
{
int n,i,j,pos;

//length of 2 strings
int len_a,len_b;

cout<<"Enter the number of names you want: ";
cin>>n;

char ch[n][100];

//character pointer for storing names
char *name[n], *temp;
cout<<"Enter the names in lowercase: "<<flush;
// buffer flushing
getchar();
for(i=0;i<n;i++)
{
gets(ch[i]);
name[i]=ch[i];
}

//selection sort
for(i=0;i<n-1;i++)
{
pos=i;
len_a=strlen(name[i]);
for(j=i+1;j<n;j++)
{
len_b=strlen(name[j]);
if(!(lexicographical_compare(name[pos],name[pos]+len_a,name[j],name[j]+len_b)))
{
pos=j;
len_a=strlen(name[pos]);
}
}
if(pos!=i)
{
temp=name[i];
name[i]=name[pos];
name[pos]=temp;
}
}
cout<<"Names in alphabetical order: "<<endl;
for(i=0;i<n;i++)
cout<<name[i]<<endl;
return 0;
}

Comments