类自定义排序的 C++ vector

标签 c++ sorting vector

我有 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/

相关文章:

C++:使用传入的字符串参数访问类型中的内容

c++ - 模板特化和DLL:Visual Studio与(GCC/Clang)

java - 相同的代码为 Java 7 和 8 产生不同的输出

algorithm - 对于大数组,选择排序比插入快吗?

c++ - 为 vector (或 STL 中的其他东西)做回调的更简单方法? C++

arrays - VHDL - std_logic_vectors 数组转换为 std_logic_vector

c++ - 在多核环境中选择 v/s 多线程

linq - 复杂对象上的 MvcContrib 网格排序

c++ - 根据一组模式对 vector 的成员重新排序

C++:为什么 unordered_set::find 比 find 快?