sort()默认排序:从小到大
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
bool comp(int &a,int &b)
{
return a < b;
}
int main()
{
vector<int> temp;
temp.push_back(55);
temp.push_back(1);
temp.push_back(99);
temp.push_back(-10);
temp.push_back(123);
sort(temp.begin(),temp.end());
for (int i = 0; i < 5; i++)
{
cout << temp[i] << " ";
}
cout << endl;
return 0;
}
sort传参实现从小到大:
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
bool comp(int &a,int &b)
{
return a < b; //或者b>a也行
}
int main()
{
vector<int> temp;
temp.push_back(55);
temp.push_back(1);
temp.push_back(99);
temp.push_back(-10);
temp.push_back(123);
sort(temp.begin(),temp.end(),comp);
for (int i = 0; i < 5; i++)
{
cout << temp[i] << " ";
}
cout << endl;
return 0;
}
sort传参实现从大到小:
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
bool comp(int &a,int &b)
{
return a > b; //或者b<a也行
}
int main()
{
vector<int> temp;
temp.push_back(55);
temp.push_back(1);
temp.push_back(99);
temp.push_back(-10);
temp.push_back(123);
sort(temp.begin(),temp.end(),comp);
for (int i = 0; i < 5; i++)
{
cout << temp[i] << " ";
}
cout << endl;
return 0;
}
PS:
sort的第三个参数必须是比较函数。
使用
bool comp(int &a,int &b)
{
return a<b;
}
和
int comp(int &a,int &b)
{
return a<b;
}
并不会报错。
但是使用以下:
int comp(int &a,int &b)
{
return true;
}
bool comp( )
{
return true;
}
int comp( )
{
return true;
}
皆会报错。