定义
template<class _RanIt> inline
void sort(_RanIt _First, _RanIt _Last)
template<class _RanIt,class _Pr> inline
void sort(_RanIt _First, _RanIt _Last, _Pr _Pred)
提供两种调用方式,一种是使用默认的<操作符(升序)比较;一种可以自定义函数
使用
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
void test01()
{
vector<int> vec{ 2, 1, 3, 4, 5, 7, 8, 6, 0 };
vec.push_back(2);
sort(vec.begin(), vec.end());
for (auto i = 0; i < vec.size(); i++)
{
cout << vec[i] << " ";
}
cout << endl;
}
//注意:必须针对相等返回false
bool compare(int a, int b)
{
return a < b;
}
void test02()
{
vector<int> vec{ 2, 1, 3, 4, 5, 7, 8, 6, 0 };
vec.push_back(2);
sort(vec.begin(), vec.end(), compare);
for (auto i = 0; i < vec.size(); i++)
{
cout << vec[i] << " ";
}
cout << endl;
}
int main()
{
test01();
test02();
system("pause");
return 0;
}
结果:
0 1 2 2 3 4 5 6 7 8
0 1 2 2 3 4 5 6 7 8
注意,第二种方式,自定义函数时,容易出现错误。
错误程序
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
bool compare(int a, int b)
{
return a >= b; //没有重复元素时,这么写不会出错
}
void test01()
{
vector<int> vec{2,1,3,4,5,7,8,6,0};
vec.push_back(2);
sort(vec.begin(),vec.end(),compare);
for (auto i = 0; i < vec.size();i++)
{
cout << vec[i] << endl;
}
}
int main()
{
test01();
system("pause");
return 0;
}
原因:元素重复
当a与b相等时,compare返回了true,这是有问题的,如果,元素不重复,则可以如上所写。
修正程序
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
bool compare(int a, int b)
{
return a > b; //去掉“=”
}
void test01()
{
vector<int> vec{2,1,3,4,5,7,8,6,0};
vec.push_back(2);
sort(vec.begin(),vec.end(),compare);
for (auto i = 0; i < vec.size();i++)
{
cout << vec[i] << endl;
}
}
int main()
{
test01();
system("pause");
return 0;
}
结论:
采用第二种方式,自定义函数时,不要出现“>=”和“=<”的情况。