要对对象成员排序,一种方法是重载比较运算符,另一种方法是自己写比较函数
#include"stdafx.h"
#include<iostream>
#include"math.h"
#include<vector>
#include<string>
#include <algorithm>
using namespace std;
class stu
{
public:
string str;
int num1;
int num2;
stu(string a, int b, int c) :str(a), num1(b), num2(c) {}
bool operator < (const stu &m)const {
return num1 < m.num1;
}
};
bool less_second(const stu & m1, const stu & m2) {
return m1.num2 < m2.num2;
}
vector<stu> input;
void output(vector<stu> &output)
{
for (auto i : input)
{
cout << i.str << " " << i.num1 << " " << i.num2 << endl;
}
}
int main()
{
stu *s1 = new stu("a", 3, 9);
input.push_back(*s1);
stu *s2 = new stu("b", 12, 12);
input.push_back(*s2);
stu *s3 = new stu("c", 30, 4);
input.push_back(*s3);
stu *s4= new stu("d", 5, 7);
input.push_back(*s4);
stu *s5 = new stu("e", 9, 2);
input.push_back(*s5);
cout << "排序前:........................" << endl;
output(input);
cout << "第一种方式排序:........................" << endl;
sort(input.begin(),input.end());
output(input);
cout << "第二种方式排序:........................" << endl;
sort(input.begin(), input.end(),less_second);
output(input);
cout << "部分排序:........................" << endl;
partial_sort(input.begin(), input.begin() + 3, input.end(),less_second);
output(input);
cout << "找出第几小:........................" << endl;
nth_element(input.begin(), input.begin() + 3, input.end());//直接数第几个即可
output(input);
int a;
cin >> a;
return 0;
}
输出:
另外还有partition和stable_partition,主要用于分类
性能排序(效率由高到低):
- partion
- stable_partition
- nth_element
- partial_sort
- sort
- stable_sort