类自定义排序的C++向量

Osc*_*car 2 c++ sorting vector

我有C++代码.有一个类的向量.我需要以一种自定义的方式对这个向量进行排序.

这是我的班级:

class Sales
{
   public:
      string customer_name;
      string category;
      string aircraft;
      string day;
      string time;
      int week;
      int ticket_price;
      string payment;

   public:
      Sales () { 
         customer_name = "";
         category = "";
         aircraft = "";
         day = "";
         time = "";
         week = 0;
         ticket_price = 0;
         payment = "";
      }

      Sales (string f_cat, string airc, string xday, string xtime, int xweek) {
         customer_name = "";
         category = f_cat;
         aircraft = airc;
         day = xday;
         time = xtime;
         week = xweek;
         ticket_price = 0;
         payment = "";
      }  
};
Run Code Online (Sandbox Code Playgroud)

让我们说:

vector <Sales> list;
Run Code Online (Sandbox Code Playgroud)

想象一下,列表已经填充了记录并且我希望将其排序为如下逻辑:

sort_string = day + time + week + category + aircraft;
Run Code Online (Sandbox Code Playgroud)

示例记录:

Sunday, 12:00, 1, Comm, b777
Monday, 10:00, 1, Comm, b777
Monday, 10:00, 1, Comm, a321
Monday, 12:00, 1, Comm, a321
Friday, 09:00, 1, Comm, a321
Run Code Online (Sandbox Code Playgroud)

预期排序:

Monday, 10:00, 1, Comm, a321
Monday, 10:00, 1, Comm, b777
Monday, 12:00, 1, Comm, a321
Friday, 09:00, 1, Comm, a321
Sunday, 12:00, 1, Comm, b777
Run Code Online (Sandbox Code Playgroud)

这可能吗?如果是,那怎么样?

谢谢.

Kir*_*rov 6

是的.

限定

bool Sales::operator<( const Sales& other ) // member
Run Code Online (Sandbox Code Playgroud)

要么

bool operator<( const Sales& lhs, const Sales& rhs) // global
Run Code Online (Sandbox Code Playgroud)

并使用std::sort.


只有两个int变量的示例,因为它们是最简单的变量:

bool operator<( const Sales& lhs, const Sales& rhs)
{
    if( lhs.week < rhs.week ) 
         return true;
    else if( lhs.week > rhs.week )  
         return false;

    if( lhs.price < rhs.price ) 
         return true;
    else if( lhs.price > rhs.price )  
         return false;

    // ...

    return false;
}
Run Code Online (Sandbox Code Playgroud)

当然,你的定义会更复杂,因为其他字段比较复杂(例如工作日),但我希望你明白这一点.

然后:

#include <algorithm>
// ...
std::sort( list.begin(), list.end() );
Run Code Online (Sandbox Code Playgroud)

顺便说一句,list变量的名称是坏的,因为std::list在某些情况下它可能会发生冲突.