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
Yes,
std::sort()
with third parameter (function or object) would be easier. An example: http://www.cplusplus.com/reference/algorithm/sort/Below is the code using lambdas
To sort a vector you can use the sort() algorithm in .
The third parameter used can be greater or less or any function or object can also be used. However the default operator is < if you leave third parameter empty.
I was curious if there is any measurable impact on performance between the various ways one can call std::sort, so I've created this simple test:
What it does is it creates a random vector, and then measures how much time is required to copy it and sort the copy of it (and compute some checksum to avoid too vigorous dead code elimination).
I was compiling with g++ (GCC) 7.2.1 20170829 (Red Hat 7.2.1-1)
Here are results:
Looks like all the options except for passing function pointer are very similar, and passing a function pointer causes +30% penalty.
It also looks like the operator< version is ~1% slower (I repeated the test multiple times and the effect persists), which is a bit strange as it suggests that the generated code is different (I lack skill to analyze --save-temps output).
A simple example using
std::sort
Edit: As Kirill V. Lyadvinsky pointed out, instead of supplying a sort predicate, you can implement the
operator<
forMyStruct
:Using this method means you can simply sort the vector as follows:
Edit2: As Kappa suggests you can also sort the vector in the descending order by overloading a
>
operator and changing call of sort a bit:And you should call sort as:
You can use user defined comparator class.