sort函数主要是用来进行特定数据类型排序的,但是呢他的使用也是有限制的,并不是想我的那般容易,他的使用的形式并不是唯一的,或者说他的使用是在特定情况下才能使用
的现在呢主要说两种,一种是比较常见的,sort排序,含义就是sort(_First,_Last,Comp);这样的一种形式,这种形式下,也就是常见的一种形式,这种形式是这样的
#include<deque>
#include<algorithm>
#include<iostream>
using namespace std;
struct stuInfo
{
int num;
char name[30];
};
//比较函数对象
bool stuCmpFunc(const stuInfo a,const stuInfo b)
{
return a.num>b.num;
}
//比较结构体
struct stuCmpStr
{
bool operator()(const stuInfo a,const stuInfo b)const
{
return a.num>b.num;
}
};
int main()
{
deque<stuInfo> stuList;
stuInfo stu_1={30,"zjy"};
stuInfo stu_2={31,"zjy"};
stuInfo stu_3={341,"zjy"};
stuInfo stu_4={34,"zjy"};
stuInfo stu_6={4,"zjy"};
stuList.push_back(stu_1);
stuList.push_back(stu_2);
stuList.push_back(stu_2);
stuList.push_back(stu_3);
stuList.push_back(stu_4);
stuList.push_back(stu_6);
cout<<"使用函数对象排序\n";
sort(stuList.begin(),stuList.end(),stuCmpFunc);
for(deque<stuInfo>::iterator itr=stuList.begin();itr!=stuList.end();itr++)
{
cout<<(*itr).num<<endl;
cout<<(*itr).name<<endl;
}
stuList.clear();
stuList.push_back(stu_1);
stuList.push_back(stu_2);
stuList.push_back(stu_2);
stuList.push_back(stu_3);
stuList.push_back(stu_4);
stuList.push_back(stu_6);
sort(stuList.begin(),stuList.end(),stuCmpStr());
cout<<"使用结构体对象排序\n";
sort(stuList.begin(),stuList.end(),stuCmpFunc);
for(deque<stuInfo>::iterator itr=stuList.begin();itr!=stuList.end();itr++)
{
cout<<(*itr).num<<endl;
cout<<(*itr).name<<endl;
}
return 0;
}
但是呢,这样并不算玩,因为呢,还有一种情况下使用sort排序,总是会出错,就是list容器,当你使用这种容器的时候,sort(_First,_Last,Comp)总是不能成功,或许是我的代码有问题吧,但是呢,使用list自身的sort函数模板也是可以成功的,如下所示,即可
#include "stdafx.h"
#include<list>
#include<algorithm>
#include<iostream>
using namespace std;
struct stuInfo
{
int num;
char name[30];
};
class cus_find
{
private :
int num;
public:
cus_find(int a):num(a)
{
;
}
bool operator()(const stuInfo a)const
{
if(a.num==num)
return true;
}
};
struct stuSort
{
bool operator()(const stuInfo a,const stuInfo b)const
{
return a.num>b.num;
}
};
bool cmp( const stuInfo& a,const stuInfo &b)
{
return a.num<b.num;
}
int _tmain(int argc, _TCHAR* argv[])
{
list<stuInfo> stuList;
stuInfo stu_1={30,"zjy"};
stuInfo stu_2={31,"zjy"};
stuInfo stu_3={341,"zjy"};
stuInfo stu_4={34,"zjy"};
stuInfo stu_6={4,"zjy"};
stuList.push_back(stu_1);
stuList.push_back(stu_2);
stuList.push_back(stu_2);
stuList.push_back(stu_3);
stuList.push_back(stu_4);
stuList.push_back(stu_6);
<strong><span style="font-size:24px;">stuList.sort(stuSort());</span></strong>
for(list<stuInfo>::iterator itr=stuList.begin();itr!=stuList.end();itr++)
{
cout<<(*itr).num<<endl;
}
list<stuInfo>::iterator itr;
itr=find_if(stuList.begin(),stuList.end(),cus_find(30));
if(itr!=stuList.end())
{
cout<<"we find the student\n";
cout<<(*itr).name<<endl;
}
return 0;
}