#2
iuyt2023-08-14 10:44
|
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
class Comparator{
public:
Comparator(){diff=0;}
virtual ~Comparator() {}
virtual bool operator()(int a,int b)=0;
int getDiff() {
return diff;
}
protected:
int diff;
};
class GT :public Comparator{
public:
bool operator()(int a,int b){
diff=a-b;
return a>b;
}
};
class LT:public Comparator{
public:
bool operator()(int a,int b){
diff=b-a;
return a<b;
}
};
int main(){
char cmd= ' ';
while(cmd != 'q'){
cout<<"请输入排序命令,l为升序排序,g为降序排序,q为退出程序"<<endl;
cin>>cmd;
if(cmd='q'){
break;
}else if(cmd!='l'&&cmd!='g'){
cout<<"不存在此命令,请重新输入:"<<endl;
continue;
}
vector<int>vec;
cout<<"请输入vector的元素个数:"<<endl;
int size=0;
cin>>size;
vec=vector<int>(size,0);
cout<<"请输入vector的元素个数,一行一个:"<<endl;
for(int i=0;i<size;i++){
cin>>vec[i];
}
if(cmd=='l'){
sort(vec.begin(),vec.end(),LT());
}else if(cmd=='g'){
sort(vec.begin(),vec.end(),GT());
}
cout<<"打印排序后的vector:"<<endl;
for(int i=0;i<vec.size();i++){
cout<<vec[i]<<"";
}
cout<<endl;
}
cout<<"退出程序......"<<endl;
return 0;
}