简体   繁体   中英

Sorting a vector of objects by a property of the object

I'm working on a project for school and need to sort some data. I've been given a vector of objects and I have to sort the objects (either in place or using an index) based on one of their properties. There are several different objects and several different properties that could it be sorted by. What's the best way to go about doing this?

Use std::sort and a functor. eg:

struct SortByX
{
   bool operator() const (MyClass const & L, MyClass const & R) { return L.x < R.x; }
};

std::sort(vec.begin(), vec.end(), SortByX());

The functor's operator() should return true if L is less than R for the sort order you desire.

There are several different objects and several different properties that could it be sorted by.

While the solution Erik posted is correct, this statement leads me to think that it's impractical at best if you are in fact planning to sort by multiple public data members of multiple classes in multiple ways in the same program, as each sorting method will require its own functor type.

I recommend the following abstraction:

#include <functional>

template<typename C, typename M, template<typename> class Pred = std::less>
struct member_comparer : std::binary_function<C, C, bool> {
    explicit member_comparer(M C::*ptr) : ptr_{ptr} { }

    bool operator ()(C const& lhs, C const& rhs) const {
        return Pred<M>{}(lhs.*ptr_, rhs.*ptr_);
    }

private:
    M C::*ptr_;
};

template<template<typename> class Pred = std::less, typename C, typename M>
member_comparer<C, M, Pred> make_member_comparer(M C::*ptr) {
    return member_comparer<C, M, Pred>{ptr};
}

Usage would look like:

#include <algorithm>
#include <string>
#include <vector>

struct MyClass {
    int         i;
    std::string s;

    MyClass(int i_, std::string const& s_) : i{i_}, s{s_} { }
};

int main() {
    std::vector<MyClass> vec;
    vec.emplace_back(2, "two");
    vec.emplace_back(8, "eight");

    // sort by i, ascending
    std::sort(vec.begin(), vec.end(), make_member_comparer(&MyClass::i));
    // sort by s, ascending
    std::sort(vec.begin(), vec.end(), make_member_comparer(&MyClass::s));
    // sort by s, descending
    std::sort(vec.begin(), vec.end(), make_member_comparer<std::greater>(&MyClass::s));
}

This will work for any type with public data members, and will save a lot of typing if you need to sort your classes more than a couple of different ways.

Here is a variation that works with public member functions instead of public data members:

#include <functional>

template<typename C, typename M, template<typename> class Pred = std::less>
struct method_comparer : std::binary_function<C, C, bool> {
    explicit method_comparer(M (C::*ptr)() const) : ptr_{ptr} { }

    bool operator ()(C const& lhs, C const& rhs) const {
        return Pred<M>{}((lhs.*ptr_)(), (rhs.*ptr_)());
    }

private:
    M (C::*ptr_)() const;
};

template<template<typename> class Pred = std::less, typename C, typename M>
method_comparer<C, M, Pred> make_method_comparer(M (C::*ptr)() const) {
    return method_comparer<C, M, Pred>{ptr};
}

With usage like:

#include <algorithm>
#include <string>
#include <vector>

class MyClass {
    int         i_;
    std::string s_;

public:
    MyClass(int i, std::string const& s) : i_{i}, s_{s} { }

    int                i() const { return i_; }
    std::string const& s() const { return s_; }
};

int main() {
    std::vector<MyClass> vec;
    vec.emplace_back(2, "two");
    vec.emplace_back(8, "eight");

    // sort by i(), ascending
    std::sort(vec.begin(), vec.end(), make_method_comparer(&MyClass::i));
    // sort by s(), ascending
    std::sort(vec.begin(), vec.end(), make_method_comparer(&MyClass::s));
    // sort by s(), descending
    std::sort(vec.begin(), vec.end(), make_method_comparer<std::greater>(&MyClass::s));
}

Here is my version of the answer, just use a lambda function! It works, it uses way less code, and in my opinion it's elegant!

#include <algorithm>
#include <vector>
#include <string>

struct MyClass
{
    int i;
    std::string s;

    MyClass(int i_, std::string const& s_) : i(i_), s(s_) { }
};

int main()
{
    std::vector<MyClass> vec;
    vec.push_back(MyClass(2, "two"));
    vec.push_back(MyClass(8, "eight"));

    // sort by i, ascending
    std::sort(vec.begin(), vec.end(), [](MyClass a, MyClass b){ return a.i < b.i; });
    // sort by s, ascending
    std::sort(vec.begin(), vec.end(), [](MyClass a, MyClass b){ return a.s < b.s; });
    // sort by s, descending
    std::sort(vec.begin(), vec.end(), [](MyClass a, MyClass b){ return a.s > b.s; });
}
sort(v.begin(), v.end(), [](const Car* lhs, const Car* rhs) {
     return lhs->getPassengers() < rhs->getPassengers();
 });

EDIT: replacing with lambda_compare, because I'm a masochist:

You can also just create a helper that lets you specify which value to use via a lambda expression:

template <class F> class lambda_compare
{
public:
    lambda_compare(F f_): f(f_) { }
    template <class T> bool operator()(const T &lhs, const T &rhs) const
    { return f(lhs)<f(rhs); }

private:
    F f;
};

template <class F> lambda_compare<F> make_lambda_compare(F f)
{ return f; }

...
std::sort(vec.begin(), vec.end(), make_lambda_compare([](const foo &value) { return value.member; }));

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