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

C++;类自定义排序向量 我有C++代码。有一个类的向量。我需要以一种有点自定义的方式对这个向量进行排序,c++,sorting,vector,C++,Sorting,Vector,这是我的班级: class Sales { public: string customer_name; string category; string aircraft; string day; string time; int week; int ticket_price; string payment; public: Sales () { custo

这是我的班级:

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 = "";
      }  
};
假设我们有:

vector <Sales> list;
示例记录:

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
预期排序:

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
这可能吗?如果是的话,怎么办

谢谢。

是的,是的

定义

bool Sales::operator<( const Sales& other ) // member
当然,您的定义会更复杂,因为其他字段比较起来更复杂(例如工作日),但我希望您能理解这一点

然后:

#包括
// ...
排序(list.begin(),list.end());

顺便说一句,
list
对于变量来说是个坏名字,因为在某些情况下它可能与
std::list
冲突。

如果要实现布尔函数作为成员,它必须是const类型

    bool operator<( const Sales& rhs) const{ 
        if (customer_name < rhs.customer_name ) return true; 
        if (category < rhs.category ) return true; 
        return false;
    }

bool运算符how
str::sort
将知道以何种顺序使用哪些变量?您可以在上面Kiril列出的函数体中定义它。@ChrisL我对此不熟悉。你能给我举个例子吗?这不是你需要的,而是一个例子。如果您想按周排序,那么您需要定义
booloperator@kiril看起来不错-省得我把它写在评论里了,我现在对你的答案投了更高的票。为什么“必须”呢?也许“应该”?直到我把它放进去,它才为我编译。@BorisIvanov这是我编译
测试时得到的结果。cpp:73:错误:在“:”token
之前这里不允许函数定义,因为
for loops
/usr/include/c++/4.8/bits/stl_algo.h:2269:19:错误:将“const Sales”作为“bool Sales::operator”的“this”参数传递
bool operator<( const Sales& lhs, const Sales& rhs) // global
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;
}
#include <algorithm>
// ...
std::sort( list.begin(), list.end() );
    bool operator<( const Sales& rhs) const{ 
        if (customer_name < rhs.customer_name ) return true; 
        if (category < rhs.category ) return true; 
        return false;
    }