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?
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.
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.
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.
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.
sort(v.begin(), v.end(), [](const Car* lhs, const Car* rhs) {
return lhs->getPassengers() < rhs->getPassengers();
});
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; });
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With