我有 C++ 代码。有一个类 vector 。我需要以有点自定义的方式对这个 vector 进行排序。
这是我的类(class):
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
这可能吗?如果是,那么如何?
谢谢。
最佳答案
是的,是的。
定义
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
冲突。
关于类自定义排序的 C++ vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20120632/