需求:
输入3个数,按照从小到大和从大到小的顺序分别排列
解决思路:
(1)导包
#include<algorithm>
(2)定义规则
①从小到大
bool bijiao(int first,int second)
{
if(first<second)
{
return true;
}
else
{
return false;
}
}
②从大到小
bool bijiao(int first,int second)
{
if(first<second)
{
return true;
}
else
{
return false;
}
}
(3)调用sort函数
sort(arr,arr+length,bijiao);
代码:(使用常规数组,从小到大排列)
#include<iostream>
using namespace std;
#include<algorithm>
bool bijiao(int first,int second)
{
if(first<second)
{
return true;
}
else
{
return false;
}
}
int main()
{
int x,y,z;
cout<<"输入:"<<endl;
cin>>x>>y>>z;
int arr[3]={0,0,0};
arr[0]=x;
arr[1]=y;
arr[2]=z;
int length=sizeof(arr)/sizeof(arr[0]);
sort(arr,arr+length,bijiao);
cout<<"输出:"<<endl;
for(int i=0;i<length;i++)
{
cout<<arr[i]<<" ";
}
cout<<endl;
}
效果:
代码:(使用常规数组,从大到小排列)
#include<iostream>
using namespace std;
#include<algorithm>
bool bijiao(int first,int second)
{
if(first>second)
{
return true;
}
else
{
return false;
}
}
int main()
{
int x,y,z;
cout<<"输入:"<<endl;
cin>>x>>y>>z;
int arr[3]={0,0,0};
arr[0]=x;
arr[1]=y;
arr[2]=z;
int length=sizeof(arr)/sizeof(arr[0]);
sort(arr,arr+length,bijiao);
cout<<"输出:"<<endl;
for(int i=0;i<length;i++)
{
cout<<arr[i]<<" ";
}
cout<<endl;
}
效果:
代码:(使用常规数组,从小到大排列)
#include<iostream>
using namespace std;
#include<algorithm>
#include<vector>
bool bijiao(int first,int second)
{
if(first<second)
{
return true;
}
else
{
return false;
}
}
int main()
{
int x,y,z;
cout<<"输入:"<<endl;
cin>>x>>y>>z;
vector<int>arr{x,y,z};
sort(arr.begin(),arr.end(),bijiao);
cout<<"输出:"<<endl;
for(int i=0;i<arr.size();i++)
{
cout<<arr[i]<<" ";
}
cout<<endl;
}
效果:
代码:(使用常规数组,从小到大排列)
#include<iostream>
using namespace std;
#include<algorithm>
#include<vector>
bool bijiao(int first,int second)
{
if(first>second)
{
return true;
}
else
{
return false;
}
}
int main()
{
int x,y,z;
cout<<"输入:"<<endl;
cin>>x>>y>>z;
vector<int>arr{x,y,z};
sort(arr.begin(),arr.end(),bijiao);
cout<<"输出:"<<endl;
for(int i=0;i<arr.size();i++)
{
cout<<arr[i]<<" ";
}
cout<<endl;
}
效果: