vector排序,支持子数组排序,sort(vec.begin(), ve.begin()+num, cmp)
#include<iostream>
#include<vector>
#include<list>
#include <algorithm>
using namespace std;
typedef struct _MyNode{
int x;
int y;
//必须用到类型名称_MyNode,这就是使用typedef的好处
_MyNode(int x, int y){
this->x=x;
this->y=y;
}
}MyNode;
void printList(vector<MyNode> l) {
vector<MyNode>::iterator iter=l.begin();
while(iter!=l.end()){
cout<<iter->x<<","<<iter->y<<endl;
iter++;
}
cout<<endl;
}
bool cmp(MyNode n1, MyNode n2){
if(n1.x==n2.x){
return n1.y<n2.y;
}
return n1.x<n2.x;
}
int main(){
//1. 自定义排序
MyNode n1(2,3), n2(1,2), n3(3,9);
vector<MyNode> l;
l.push_back(n1);
l.push_back(n2);
l.push_back(n3);
printList(l);
sort(l.begin(), l.end(), cmp);
printList(l);
//2. 自然顺序排序
vector<int> l2;
l2.push_back(4);
l2.push_back(3);
l2.push_back(1);
l2.push_back(6);
sort(l.begin(), l.begin()+3);
/*
vector<int>::iterator iter2=l2.begin();
while(iter2!=l2.end()){
cout<<*iter2<<endl;
}
*/
cout<<endl;
return 0;
}
list排序,只支持整体排序,l.sort(cmp)
#include<iostream>
#include<vector>
#include<list>
#include <algorithm>
using namespace std;
typedef struct _MyNode{
int x;
int y;
_MyNode(int x, int y){
this->x=x;
this->y=y;
}
}MyNode;
void printList(list<MyNode> l) {
list<MyNode>::iterator iter=l.begin();
while(iter!=l.end()){
cout<<iter->x<<","<<iter->y<<endl;
iter++;
}
cout<<endl;
}
bool cmp(MyNode n1, MyNode n2){
if(n1.x==n2.x){
return n1.y<n2.y;
}
return n1.x<n2.x;
}
int main(){
//1. list<...>只能全部排序, 而且调用的是list的public方法sort(cmp),不是<algorithm>头文件中的函数sort()
MyNode n1(2,3), n2(1,2), n3(3,9);
list<MyNode> l;
l.push_back(n1);
l.push_back(n2);
l.push_back(n3);
printList(l);
l.sort(cmp);
printList(l);
return 0;
}