Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting a vector of objects by a property of the object

Tags:

c++

sorting

std

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?

like image 286
s00pcan Avatar asked Mar 02 '11 22:03

s00pcan


People also ask

How do you sort a vector of an object?

You can sort a vector of custom objects using the C++ STL function std::sort. The sort function has an overloaded form that takes as arguments first, last, comparator. The first and last are iterators to first and last elements of the container.

How do you sort the structure of a vector?

A vector in C++ can be easily sorted in ascending order using the sort() function defined in the algorithm header file. The sort() function sorts a given data structure and does not return anything. The sorting takes place between the two passed iterators or positions.

Can we sort constant vector?

Yes it can be done but marking something as a const is meant to be a contract. Other pieces of code will make assumptions based on it being constant.


4 Answers

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.

like image 187
Erik Avatar answered Oct 25 '22 02:10

Erik


sort(v.begin(), v.end(), [](const Car* lhs, const Car* rhs) {
     return lhs->getPassengers() < rhs->getPassengers();
 });
like image 33
Jaziri Rami Avatar answered Oct 25 '22 00:10

Jaziri Rami


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));
}
like image 45
ildjarn Avatar answered Oct 25 '22 01:10

ildjarn


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; });
}
like image 40
Steven McConnon Avatar answered Oct 25 '22 00:10

Steven McConnon