我有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 = "";
}
};
让我们说:
vector <Sales> list;
想象一下,列表已经填充了记录我希望将其排序如下逻辑:
sort_string = day + time + week + category + aircraft;
示例记录:
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
这可能吗?如果是,那怎么样?
感谢。
答案 0 :(得分:6)
是的,确实如此。
定义
bool Sales::operator<( const Sales& other ) // member
或
bool operator<( const Sales& lhs, const Sales& rhs) // global
并使用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;
}
当然,你的定义会更复杂,因为其他字段比较复杂(例如工作日),但我希望你明白这一点。
然后:
#include <algorithm>
// ...
std::sort( list.begin(), list.end() );
顺便说一下,list
是变量的坏名称,因为在某些情况下它可能与std::list
冲突。
答案 1 :(得分:0)
如果你将布尔函数实现为成员,它必须是const类型
bool operator<( const Sales& rhs) const{
if (customer_name < rhs.customer_name ) return true;
if (category < rhs.category ) return true;
return false;
}
见工作example