How does one go about sorting a vector containing custom (i.e. user defined) objects.
Probably, standard STL algorithm sort along with a predicate (a function or a function object) which would operate on one of the fields (as a key for sorting) in the custom object should be used.
Am I on the right track?
相关问题
- Sorting 3 numbers without branching [closed]
- How to toggle on Order in ReactJS
- PHP Recursively File Folder Scan Sorted by Modific
- How to compile C++ code in GDB?
- Why does const allow implicit conversion of refere
相关文章
- Class layout in C++: Why are members sometimes ord
- How to mock methods return object with deleted cop
- Which is the best way to multiply a large and spar
- C++ default constructor does not initialize pointe
- Selecting only the first few characters in a strin
- What exactly do pointers store? (C++)
- Converting glm::lookat matrix to quaternion and ba
- What is the correct way to declare and use a FILE
You are on the right track.
std::sort
will useoperator<
as comparison function by default. So in order to sort your objects, you will either have to overloadbool operator<( const T&, const T& )
or provide a functor that does the comparison, much like this:The advantage of the usage of a functor is that you can use a function with access to the class' private members.
You could use functor as third argument of
std::sort
, or you could defineoperator<
in your class.if compare is false, it will do "swap".
Sorting such a
vector
or any other applicable (mutable input iterator) range of custom objects of typeX
can be achieved using various methods, especially including the use of standard library algorithms likesort
,stable_sort
,partial_sort
orpartial_sort_copy
.Since most of the techniques, to obtain relative ordering of
X
elements, have already been posted, I'll start by some notes on "why" and "when" to use the various approaches.The "best" approach will depend on different factors:
X
objects a common or a rare task (will such ranges be sorted a mutiple different places in the program or by library users)?X
objects be foolproof?If sorting ranges of
X
is a common task and the achieved sorting is to be expected (i.e.X
just wraps a single fundamental value) then on would probably go for overloadingoperator<
since it enables sorting without any fuzz (like correctly passing proper comparators) and repeatedly yields expected results.If sorting is a common task or likely to be required in different contexts, but there are multiple criteria which can be used to sort
X
objects, I'd go for Functors (overloadedoperator()
functions of custom classes) or function pointers (i.e. one functor/function for lexical ordering and another one for natural ordering).If sorting ranges of type
X
is uncommon or unlikely in other contexts I tend to use lambdas instead of cluttering any namespace with more functions or types.This is especially true if the sorting is not "clear" or "natural" in some way. You can easily get the logic behind the ordering when looking at a lambda that is applied in-place whereas
operator<
is opague at first sight and you'd have to look the definition up to know what ordering logic will be applied.Note however, that a single
operator<
definition is a single point of failure whereas multiple lambas are multiple points of failure and require a more caution.If the definition of
operator<
isn't available where the sorting is done / the sort template is compiled, the compiler might be forced to make a function call when comparing objects, instead of inlining the ordering logic which might be a severe drawback (at least when link time optimization/code generation is not applied).Ways to achieve comparability of
class X
in order to use standard library sorting algorithmsLet
std::vector<X> vec_X;
andstd::vector<Y> vec_Y;
1. Overload
T::operator<(T)
oroperator<(T, T)
and use standard library templates that do not expect a comparison function.Either overload member
operator<
:or free
operator<
:2. Use a function pointer with a custom comparison function as sorting function parameter.
3. Create a
bool operator()(T, T)
overload for a custom type which can be passed as comparison functor.Those function object definitions can be written a little more generic using C++11 and templates:
which can be used to sort any type with member
i
supporting<
.4. Pass an anonymus closure (lambda) as comparison parameter to the sorting functions.
Where C++14 enables a even more generic lambda expression:
which could be wrapped in a macro
making ordinary comparator creation quite smooth:
In your class, you may overload the "<" operator.
In the interest of coverage. I put forward an implementation using lambda expressions.
C++11
C++14