debai23
//Bai 23
//Lop doi tuong xau ky tu
#include<iostream>
#include<string.h>
using namespace std;
//Khai bao lop xau ky tu
class XString
{
private:
char* s;
long size;
public:
XString():s(new char[256]),size(256)
{ }
XString(char* str);
XString(const XString& s1);
void input();
void show();
XString& operator=(const XString& r);
XString& operator+(const XString& r);
int operator<(const XString& r);
int operator>(const XString& r);
int operator<=(const XString& r);
int operator>=(const XString& r);
int operator==(const XString& r);
int operator!=(const XString& r);
XString getLWord();
~XString()
{
delete [] s;
}
};
//nen dung ham chuan hoa' xau dung de cat bo dau cach o 2 dau cua xau do
//Ve nha lam them ham chong toan tu cin va cout
//==========CHUONG TRINH CHINH=========
int main()
{
int n,i,j;
XString tg;
cout<<"Nhap vao so luong ho ten: ";cin>>n;cin.ignore();
XString* ds=new XString[n];
cout<<"Nhap danh sach ho ten:
";
for(i=0;i<n;i++)
{
cout<<"\tHo ten nguoi thu "<<(i+1)<<": ";
ds[i].input();
}
//Sap xep
for(i=0;i<n-1;i++)
for(j=i+1;j<n;j++)
if(ds[j].getLWord()<ds[i].getLWord())
{
tg=ds[i];ds[i]=ds[j];ds[j]=tg;
}
cout<<"Danh sach ho ten da sap xep la:
";
cout.setf(ios::left);
cout.width(5);cout<<"STT";
cout.width(40);cout<<"Ho va ten"<<endl;
for(i=0;i<n;i++)
{
cout.width(5);cout<<(i+1);
cout.width(40);ds[i].show();
cout<<endl;
}
delete [] ds;
return 0;
}
//=======DINH NGHIA CAC HAM============
XString::XString(char* str)
{
size=strlen(str)+1;
s=new char[size];
strcpy(s,str);
}
XString::XString(const XString& s1)
{
size=strlen(s1.s)+1;
s=new char[size];
strcpy(s,s1.s);
}
void XString::input()
{
cin.get(s,size);cin.ignore();//sizeof()khong duoc dung. Neu dung se la do dai cua con tro xau ky tu ma khong phai la xau ky tu do, ma phai dung size thi moi dung
}
void XString::show()
{
cout<<s;
}
XString& XString::operator=(const XString& r)
{
delete [] s;
size=strlen(r.s)+1;
s=new char[size];
strcpy(s,r.s);
}
XString& XString::operator+(const XString& r)
{
if(strlen(s)+strlen(r.s)>=size)
{
cout<<"Vuot qua do dai cua xau => khong ghep duoc";
return *this;
}
else strcat(s,r.s);
return *this;
}
int XString::operator<(const XString& r)
{
if(strcmp(s,r.s)<0) return 1;
return 0;
}
int XString::operator>(const XString& r)
{
if(strcmp(s,r.s)>0) return 1;
return 0;
}
int XString::operator<=(const XString& r)
{
if(!strcmp(s,r.s)>0) return 1;
return 0;
}
int XString::operator>=(const XString& r)
{
if(!strcmp(s,r.s)<0) return 1;
return 0;
}
int XString::operator==(const XString& r)
{
if(strcmp(s,r.s)==0) return 1;
return 0;
}
int XString::operator!=(const XString& r)
{
if(strcmp(s,r.s)!=0) return 1;
return 0;
}
XString XString::getLWord()//Khi p chua tro vao ki tu dau tien thi con lui
{
char* p=s+strlen(s)-1;
while(*p!=' ' && p!=s) p--;
if(p!=s) p++;//vi phai kiem tra xem p da tro vao ki tu dau tien chua
return XString(p);//day la ham tao mot doi so voi cai tra ve la mot doi tuong
}
Bạn đang đọc truyện trên: AzTruyen.Top