vector用sort算法排序

来源:互联网 发布:2017淘宝同城交易规则 编辑:程序博客网 时间:2024/05/29 18:12

用sort对vector排序有两种方法
方法1:
#include <vector>//容器的头文件
#include <algorithm> //sort算法用到的头文件
using namespace std;

  struct Info
{
 int x;
 bool operator >(const Info& Pinfo) const;  //降序排列需要重载的操作符
 bool operator <(const Info& pinfo) const;  //升序排列需要重载的操作符
};
bool Info::operator >(const Info& pinfo) const
{
 return x>pinfo.x;
}
bool Info::operator<(const Info& pinfo) const
{
 return x
}
int main(int argc, char* argv[])
{    vector m_vecInfo;
     for (int i=0;i<10;i++)
     {
      Info pInfo;
      pInfo.x=i;
      m_vecInfo.push_back(pInfo);
     }
 sort(m_vecInfo.begin(),m_vecInfo.end(),greater());//降序排列
 sort(m_vecInfo.begin(),m_vecInfo.end(),less()); //升序排列
 return 0;
}
 
方法2:
#include <vector>//容器的头文件
#include <algorithm> //sort算法用到的头文件
using namespace std;
 
struct Info {int x;};
bool copare(const Info* pfirst,const Info* psecond) //如果该vector存入的是对象的话该函数参数须是
{                                                    // 对象的引用,而不该是指针
 return pfirst->x>=psecond->x;
}
int main(int argc, char* argv[])
{ vector m_vecInfo;
Info* pInfo;
for (int i=0;i<10;i++)
{
pInfo = new Info;
pInfo->x=i;
m_vecInfo.push_back(pInfo);
}
sort(m_vecInfo.begin(),m_vecInfo.end(),copare); //按照自己写的排序函数进行排序
return 0;
}
总结:这两个方法都可实现vector的排序,当vector存入的是对象时两种方法都行(只要把第二种方法的用于排序的分成员函数的参数列表写成对象的引用即可),但是当vector里是指针的时候只能用第二种方法进行排序。
应该还有别的方法,但是我没有测试过,因此只介绍这两种方法。

0 0