10

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?

s00pcan
  • 163
  • 1
  • 2
  • 9

5 Answers5

20

Use std::sort and a functor. e.g:

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.

Erik
  • 88,732
  • 13
  • 198
  • 189
14

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));
}
ildjarn
  • 62,044
  • 9
  • 127
  • 211
  • This worked, but how do I use it without making the data members public? – s00pcan Mar 04 '11 at 19:39
  • @s00pcan : Taking the address of an inaccessible data member is illegal, so this approach only works for public data members. However, this code could be trivially modified to work with public "getter" member functions instead. – ildjarn Mar 04 '11 at 20:23
  • trivial, probably, but it's not obvious to me what to change. – s00pcan Mar 04 '11 at 23:10
  • I'm trying to do this using a function pointer but I'm getting an error about invalid access to non-static methods. The function pointer works fine in a trivial example, not sure yet why it's doing it with my existing code. – s00pcan Mar 04 '11 at 23:34
  • @s00pcan : I've edited my answer to include the code for member function rather than data member usage. – ildjarn Mar 05 '11 at 00:34
  • had some issues regarding the consts, but this worked. Thank you. – s00pcan Mar 05 '11 at 01:49
  • @s00pcan : 'Getter' member functions *should* be `const` -- if yours aren't then your classes likely suffer from lack of 'const correctness': http://www.parashift.com/c++-faq-lite/const-correctness.html – ildjarn Mar 05 '11 at 02:18
  • I would give this answer more than 1 upvote, if I could. Great piece of code. Thanks. – AudioDroid Aug 24 '11 at 13:22
5

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; });
}
Steven McConnon
  • 2,650
  • 2
  • 16
  • 21
2
sort(v.begin(), v.end(), [](const Car* lhs, const Car* rhs) {
     return lhs->getPassengers() < rhs->getPassengers();
 });
Donald Duck
  • 8,409
  • 22
  • 75
  • 99
Jaziri Rami
  • 147
  • 1
  • 12
  • While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value. – Donald Duck Dec 22 '20 at 12:09
1

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; }));
MSN
  • 53,214
  • 7
  • 75
  • 105