Reputation: 243
I have C++ code. There is a vector of class. I need to sort this vector in a bit custom way.
Here is my 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 = "";
}
};
Lets say we have:
vector <Sales> list;
Imagine that list has got populated record And I want to get this sorted like below logic:
sort_string = day + time + week + category + aircraft;
Example records:
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
Expected Sort:
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
Is this possible? if Yes, then how?
Thanks.
Upvotes: 3
Views: 287
Reputation: 4254
if you will implement boolean function as member it must be const type
bool operator<( const Sales& rhs) const{
if (customer_name < rhs.customer_name ) return true;
if (category < rhs.category ) return true;
return false;
}
See working example
Upvotes: 0
Reputation: 38173
Yes, it is.
Define
bool Sales::operator<( const Sales& other ) // member
or
bool operator<( const Sales& lhs, const Sales& rhs) // global
and use std::sort
.
Example with only two int
variables, as they are the easiest ones:
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;
}
Of course, your definition will be more complicated, because the other fields are more complicated for comparing (the weekday for example), but I hope you get the point.
Then:
#include <algorithm>
// ...
std::sort( list.begin(), list.end() );
By the way, list
is bad name for variable, as it may conflict with std::list
in some cases.
Upvotes: 7