简体   繁体   中英

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<

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?)

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

3.using custom compare functions

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. This function should behave as < between elements (ie return true when the first is "less than" the second.

For example to sort an std::vector of your structures on increasing payment value what you can do is:

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) ;

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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