Overload the Logical Operators to Sort Strings Alphabetically
In c++, we have function like strcmp(const char* c1,const char* c2) to help us decide which is alphabetically before the other. Yet we still want to use a more easy-going function as a bool operator < or something else like other logical operators.
And here we have a customized user-define class String, which is incomplete due this is only for demonstration of overloading operators.
#include <iostream>
#include <iomanip>
using namespace std;
class String{
char* chars;
public:
int length;
String String::operator =(const char* r){
length=strlen(r);
chars=(char*)malloc((length+1)*sizeof(char));
for(int i=0;i<=length;i++){
this->chars[i]=r[i];
}
return *this;
}
String String::operator =(String r){
length=r.length;
chars=(char*)malloc((length+1)*sizeof(char));
for(int i=0;i<=length;i++){
this->chars[i]=r[i];
}
return *this;
}
char &String::operator [](int idx){
return chars[idx];
}
bool operator <(String r)
{
for(int idx=0;idx<=(length<r.length?length:r.length);idx++)
{
if(tolower(chars[idx])<tolower(r[idx]))
return true;
else
if(tolower(chars[idx])>tolower(r[idx]))
return false;
else
continue;
}
return false;
}
bool operator >(String r)
{
return r<*this;
}
bool operator ==(String r)
{
return !(*this>r)&&!(*this<r);
}
bool operator !=(String r)
{
return !(*this==r);
}
bool operator <=(String r)
{
return !(*this>r);
}
bool operator >=(String r)
{
return !(*this<r);
}
friend ostream&operator <<(ostream &os,String &right);
friend istream&operator <<(istream &is,String &right);
String(int n){
length=n;
chars=new char[length];
}
String (){
length=0;
}
String (const char* cs){
*this=cs;
}
};
ostream & operator<<(ostream &os, String &right)
{
for(int i=0;i<=right.length;i++)
{
os<<right[i];
}
return os;
}
istream & operator>>(istream &is,String &right)
{
int idx=2;
char* tmpcs=new char[idx];
char c;
int i=0;
for(;;i++)
{
c=is.get();
if(c!='n')
{
if(i>=idx)
{
idx=i+1;
tmpcs=(char*)realloc(tmpcs,idx*sizeof(char));
}
if(isalpha(c))
{
tmpcs[i]=c;
}
}
else
{
if(i>=idx)
{
idx=i+1;
tmpcs=(char*)realloc(tmpcs,idx*sizeof(char));
}
tmpcs[i]='';
break;
}
}
right=tmpcs;
return is;
}
template <typename T>
void sort(T *source,int startidx,int endidx)
{
for(int i=startidx+1;i<=endidx;i++)
{
for(int j=startidx;j<i;j++)
{
if(source[i]<source[j])
{
T key=source[i];
for(int k=i;k>j;k--)
{
source[k]=source[k-1];
}
source[j]=key;
break;
}
}
}
}
int main()
{
String group[5];
cout<<"Please input 5 words"<<endl;
for(int i=0;i<5;i++)
{
cin>>group[i];
}
sort(group,0,4);
cout<<"after the sorting"<<endl;
for(int i=0;i<5;i++)
{
cout<<group[i]<<endl;
}
system("pause");
return 0;
}