要求:有一個關於學生資訊的結構體數組,有班級,成績,年齡等資訊,現要求一學生班級為主關鍵字排序,如果班級相同,則按照成績排序,如果成績相同,則按照年齡排序。
參考代碼
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
struct student
{
int Class;
int rank;
int age;
};
vector<student> stu;
bool cmp(const student &a,const student &b)
{
if(a.Class!=b.Class)
{
return a.Class<b.Class;
}
else if(a.rank!=b.rank)
{
return a.rank<b.rank;
}
else
{
return a.age<b.age;
}
}
int main()
{
student tmp;
int num = 5;
while(num--)
{
cin>>tmp.Class>>tmp.rank>>tmp.age;
stu.push_back(tmp);
}
sort(stu.begin(),stu.end(),cmp);
for(int i=0;i<5;i++)
{
cout<<stu[i].Class<<"\t"<<stu[i].rank<<"\t"<<stu[i].age<<endl;
}
system("pause");
return 0;
}
參考資料:
1 4 1
1 3 3
2 3 3
2 3 1
4 2 3
運行結果:
要求:
有一字串,由字母和數字組成,字母有大寫和小寫之分,現要使數字夾在小寫字母和大寫字母之間,而且字母遵循字典序,數字從小到大排序。
參考資料:
ofahIUGH5092foiIUIOq2t02ogihaohgawi5209GHAOIUHG
參考代碼:
#include <iostream>
#include <algorithm>
#define SIZE 100
#define Is_Num(x) (x<='9'&&x>='0')
#define Is_LowCase(x) (x>='a'&&x<='z')
#define Is_UpCase(x) (x>='A'&&x<'Z')
using namespace std;
bool cmp(const char &a,const char &b)
{
if(Is_Num(a)&&Is_Num(b))
{
return a<b;
}
else if(Is_LowCase(a)&&Is_LowCase(b))
{
return a<b;
}
else if(Is_UpCase(a)&&Is_UpCase(b))
{
return a<b;
}
else if(Is_Num(a)&&Is_LowCase(b))
{
return true;
}
else if(Is_Num(b)&&Is_LowCase(a))
{
return false;
}
else if(Is_Num(a)&&Is_UpCase(b))
{
return false;
}
else if(Is_Num(b)&&Is_UpCase(a))
{
return true;
}
else if(Is_LowCase(a)&&Is_UpCase(b))
{
return false;
}
else if(Is_LowCase(b)&&Is_UpCase(a))
{
return true;
}
}
int main()
{
char a[SIZE];
while(cin>>a)
{
int len = strlen(a);
sort(a,a+len,cmp);
cout<<"after sort:"<<endl;
cout<<a<<endl;
}
return 0;
}
運行結果:
要求:給一堆數字,有正有負,要求把所有的負數拿到正數前面來,且正數與正數的相對位置,負數與負數的相對位置都不能變。
參考資料:
15
3 4 -3 4 -5 -8 5 1 6 -2 5 -1 5 -3 -4
參考代碼:
#include <iostream>
#include <algorithm>
#define SIZE 100
using namespace std;
bool cmp(const int &a,const int &b)
{
if(a<0&&b>0)
{
return true;
}
return false;
}
int main()
{
int array[SIZE];
int length;
while(cin>>length)
{
for(int i=0;i<length;i++)
{
cin>>array[i];
}
sort(array,array+length,cmp);
cout<<"after sort:"<<endl;
for(int i=0;i<length;i++)
{
cout<<array[i]<<" ";
}
}
return 0;
}
運行結果:
最後 cmp函數可以用greater<int>();(按總大到小的順序排序)less<int>();(從小到大排序)。