https://blog.csdn.net/lethic/article/details/7781203
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
typedef struct example
{
int elem1;
int elem2;
}example;
/*这个comparison函数很重要.如果希望升序排序,就是"<",降序排列就是">"号,这样便于直观记忆.如果希望用elem2作为比较标准
就把elem1改为elem2,这样结构体就以elem2为比较标准排序了.*/ bool comparison(example a,example b){
return a.elem1<b.elem1;
}
int main()
{
int N;
fin>>N;
vector<example> array(N);
for(int i=0;i<N;i++)
{
fin>>array[i].elem1>>array[i].elem2;
}
sort(array.begin(),array.end(),comparison);
for(int i=0;i<N;i++)
{
cout<<array[i].elem1<<" "<<array[i].elem2<<endl;
}
return 0;
}
***********************************************************************
[http://www.bubuko.com/infodetail-3443696.html](https://)
重写仿函数(函数指针法)
#include<iostream>
#include<algorithm>
using namespace std;
struct stu{
int num;
float score;
};
bool cmp(const stu &a, const stu &b){
return a.score < b.score;
}
int main(){
stu nums[3] = {{1,98.5}, {2,88.5}, {3,68.5}};
sort(nums, nums + 3, cmp);
for(int i = 0; i < 3; ++ i)
{
cout << nums[i].score <<endl;
}
return 0;
}
重载运算符(struct内部 + struct外部)
#include<iostream>
#include<algorithm>
using namespace std;
struct stu{
int num;
float score;
bool operator<(const stu &a) const
{
return score < a.score;
}
};
int main(){
stu nums[3] = {{1,98.5}, {2,88.5}, {3,68.5}};
sort(nums, nums + 3);
for(int i = 0; i < 3; ++ i)
{
cout << nums[i].score <<endl;
}
return 0;
}
#include<iostream>
#include<algorithm>
using namespace std;
struct stu{
int num;
float score;
};
bool operator<(const stu &a, const stu &b)
{
return a.score < b.score;
}
int main(){
stu nums[3] = {{1,98.5}, {2,88.5}, {3,68.5}};
sort(nums, nums + 3);
for(int i = 0; i < 3; ++ i)
{
cout << nums[i].score <<endl;
}
return 0;
}