stable_sort定义
template <class RandomAccessIterator>
void stable_sort ( RandomAccessIterator first, RandomAccessIterator last );
template <class RandomAccessIterator, class Compare>
void stable_sort ( RandomAccessIterator first, RandomAccessIterator last,
Compare comp );
第三个参数comp
:
它是一个二元函数,返回一个bool
值。他决定了第一个元素是否在第二个前面,简单来说,如果返回true
顺序就是参数顺序,反之,则是参数反序。
Binary function that accepts two elements in the range as arguments, and returns a value convertible to bool. The value returned indicates whether the element passed as first argument is considered to go before the second in the specific strict weak ordering it defines.
The function shall not modify any of its arguments.
This can either be a function pointer or a function object.
用法
#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
using namespace std;
struct student
{
student(string name ,int id,double stature):m_name(name),m_id(id),m_stature(stature){}
string m_name; //名字
int m_id; //学号
double m_stature; //身高
};
//student对象从高到低排列
bool comp(student s1, student s2)
{
return s2.m_stature<s1.m_stature;
}
int main()
{
student stud1("XiaoMing", 1, 170.22);
student stud2("LiLei", 2, 165.33);
student stud3("XiaoHong", 3, 156.89);
vector<student> students={ stud1 ,stud2 ,stud3 };
stable_sort(students.begin(), students.end(), comp);
for (auto s : students)
{
cout << s.m_stature << endl;
}
return 0;
}