mardi 27 décembre 2016

How to sort vector by specific attribute which is field of contained object

To make it as clear as possible. I got a class named: Rental which contains Client*

 class Rental
{
  private:
    boost::uuids::uuid UUID;
    boost::posix_time::ptime date_start;
    boost::posix_time::ptime date_end;
    int daysOfRent;
    double costOfRent;
    Vehicle* vehicle;
    Client* client;
 ...
};

and class Client

class Client
{
private:
    std::string name;
    std::string surname;
    double balance;
    double discount;
    ClientType *clientType;
...
};

Is there anyway to sort vector which is represented as

  std::vector<Rental*> rents;

by surnames of clients ?

my first guess was with using functor, but I have no idea how could I do this really.

std::vector<Rental*> rents;
std::sort(rents.begin(), rents.end(), [](const Client* fc, const Client* sc)
    {return fc->getSurname() < sc->getSurname();
});

I know that doesn't make any sense, that's why I'm asking as I couldnt find any direct answer among other posts.

Aucun commentaire:

Enregistrer un commentaire