In C ++, can you easily sort a vector of object type pointers with respect to any attribute of these objects?

Is it possible to easily sort the vector of object type pointers with respect to any attribute of these objects?

Let's say students- this is a vector of object type pointers when the object studentis a type studentand has two methods student.studentAlias()and student.studentName(). How can I sort a vector by alias?

Thanks in advance.

+3
source share
3 answers

You can use the functor:

#include <vector>
#include <algorithm>

class StudentAliasComparator
{
public:
    bool operator()(const Student* left, const Student* right) const
    {
        return left->studentAlias() < right->studentAlias();
    }
};

void SortVectorOfStudentByAlias(std::vector<Student*>& students)
{
    std::sort(students.begin(), students.end(), StudentAliasComparator());
}

boost, langage ( ++ 0x). ++ 0x - ( , ++, ++ 0x ):

void SortVectorOfStudentByAlias(std::vector<Student*>& students)
{
    std::sort(students.begin(), students.end(),
        [](const Student* l, const Student* r) {
            return l->studentAlias() < r->studentAlias(); })
}
+13

std:: sort:

template <class RandomAccessIterator, class StrictWeakOrdering>
void sort(RandomAccessIterator first, RandomAccessIterator last, StrictWeakOrdering comp);

(comp), , .

+5

std::mem_fun :

#include <algorithm>
#include <functional>

template <typename F>
struct CompareBy
{
    bool operator()(const typename F::argument_type& x,
                    const typename F::argument_type& y)
    { return f(x) < f(y); }

    CompareBy(const F& f) : f(f) {}

 private:
    F f;
};

template <typename F>
CompareBy<F> by(const F& f) { return CompareBy<F>(f); }

, do

std::vector<Student*> students;

std::sort(students.begin(), students.end(), 
          by(std::mem_fun(&Student::studentAlias))
);

-, , std::mem_ptr. , .

+2

All Articles