简体   繁体   English

在C ++中按结构成员对列表进行排序

[英]Sorting a list by a struct member in c++

I have a list filled with this struct: 我有一个列表填充此结构:

struct singlePaymentStruct
{
    std::string payer;      
    int payment;            
    double amount;          
    std::time_t timeRec;    

    singlePaymentStruct() {
                            payer="Empty"; 
                            payment=0; 
                            amount=0;
                            timeRec = time(0);
                          }
};

I want to be able to sort this list by any of the fields. 我希望能够按任何字段对该列表进行排序。 How exactly do I do this? 我到底该怎么做? I didn't quite understand how sort method works with something more complex than just a list of records... 我不太了解排序方法如何处理比仅记录列表更复杂的内容...

Solution found: 找到解决方案:

singlePaymentList.sort( []( const singlePaymentStruct &a, const singlePaymentStruct &b)
                                                          {return a.payer > b.payer;} 
                      );

1.overloading operator< 1.重载运算符<

you can do this by overloading the < operator 您可以通过重载<运算符来实现

struct Foo{
    int bar;
    bool operator<(Foo &x){
        return bar < x.bar;
    }
};

2.using lambda expressions (what is lambda expression?) 2.使用lambda表达式 (什么是lambda表达式?)

Foo array[10];
std::sort(array,array + 10,[](Foo const &l, Foo const &r) { 
          return l.bar < r.bar; });

3.using custom compare functions 3,使用自定义比较功能

If the possible fields to be used for sorting are known prior, it may be easier to read to implement custom compare functions specifically for the sorting. 如果用于排序的可能字段是事​​先已知的,则可能更容易阅读以实现专门用于排序的自定义比较功能。

struct Foo {
  int bar;
  SpecialType daa;  // Assume daa.IsLessThan() available.

  static bool lessBar(const Foo& l, const Foo& r) {
    return l.bar < r.bar;
  }
  static bool lessDaa(const Foo& l, const Foo& r) {
    return l.daa.IsLessThan(r.daa);
  }
};

Foo array1[10];  // To be sorted by Foo::bar
Foo array2[10];  // To be sorted by Foo::daa
std::sort(array1, array1+10, Foo::lessBar);
std::sort(array2, array2+10, Foo::lessDaa);

std::sort accepts a third optional parameter that is a comparator function. std::sort接受第三个可选参数,它是比较器函数。 This function should behave as < between elements (ie return true when the first is "less than" the second. 此函数应在元素之间表现为< (即第一个元素“小于”第二个元素时返回true

For example to sort an std::vector of your structures on increasing payment value what you can do is: 例如,在增加payment金额时对结构的std::vector进行排序,您可以做的是:

std::sort(data.begin(), data.end(),
          [](const singlePaymentStruct& a, const singlePaymentStruct& b) {
              return a.payment < b.payment;
          });

let the array be struct singlePaymentStruct a[N] sort(a,a+N,cmp) ; 令数组为struct singlePaymentStruct a[N] sort(a,a+N,cmp)

bool cmp(struct singlePaymentStruct x, struct singlePaymentStruct y)
{
   return x.field < y.field ; //or anything you want to do and return boolean
}

How it works under the hood? 它是如何工作的?

Simply put basically it uses some sorting algoritm like quicksort or mergesort. 简单地说,它基本上使用了一些排序算法,例如quicksort或mergesort。

Why do we specify comparator functor ? 为什么要指定比较器函子?

Well we need that comparator functor to decide the ordering of elements. 好吧,我们需要比较器函子来确定元素的顺序。 The basic thing is in any sorting algortihm the basic operation is comparison..and if we can specify that we are basically controlling the sorting operation. 基本的东西在任何排序算法中,基本的操作都是比较。如果可以指定我们基本上是在控制排序操作。

Hope now you get the pieces together. 希望现在您能拼凑起来。 That's why cmp() takes two values which it will compare and based on which order them. 这就是为什么cmp()会采用两个值进行比较并基于它们的顺序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM