STL中sort用法小例項
阿新 • • 發佈:2019-01-01
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
#define stlforeach(type,iter,container) type::iterator iter;for(iter=(container).begin();iter!=(container).end();++iter)
struct Node{
int id;
int num;
Node(int iid=0,int inum=0)
:id(iid),num(inum){}
};
bool compable(const Node&n1,const Node& n2)
{
if(n1.id<n2.id)
return true;
else if(n1.id==n2.id)
return n1.num<=n2.num;
else
return false;
}
int main()
{
vector<Node> v;
Node n1(1,3);
Node n2(1,4);
Node n3(3,4);
v.push_back(n1);
v.push_back(n3);
v.push_back(n2);
stlforeach(vector<Node>,iter,v)
{
cout<<iter->id<<endl;
}
sort(v.begin(),v.end(),compable);
cout<<"paixurgk"<<endl;
stlforeach(vector<Node>,iter2,v)
{
cout<<iter2->id<<endl;
}
return 0;
}
#include<vector>
#include<algorithm>
using namespace std;
#define stlforeach(type,iter,container) type::iterator iter;for(iter=(container).begin();iter!=(container).end();++iter)
struct Node{
int id;
int num;
Node(int iid=0,int inum=0)
:id(iid),num(inum){}
};
bool compable(const Node&n1,const Node& n2)
{
if(n1.id<n2.id)
return true;
else if(n1.id==n2.id)
return n1.num<=n2.num;
else
return false;
}
int main()
{
vector<Node> v;
Node n1(1,3);
Node n2(1,4);
Node n3(3,4);
v.push_back(n1);
v.push_back(n3);
v.push_back(n2);
stlforeach(vector<Node>,iter,v)
{
cout<<iter->id<<endl;
}
sort(v.begin(),v.end(),compable);
cout<<"paixurgk"<<endl;
stlforeach(vector<Node>,iter2,v)
{
cout<<iter2->id<<endl;
}
return 0;
}