C++ || How To Sort An Array/Vector/Container With Multiple Sorting Conditions Using C++

The following is a module with functions which demonstrates how to sort an array/vector/container with multiple sorting conditions using C++.

The function demonstrated on this page is a wrapper for the std::sort function, which means it works for any container supported by std::sort.

This function accepts multiple sorting conditions (comparison functions), which allows for complex array sorting much like the SQL/LINQ ‘Order By’ operation.


1. Simple Array – Ascending

The example below demonstrates the use of Utils::sortBy to sort a simple array.

In this example, no sorting conditions are specified. In this case, the array is sorted in ascending order.


2. Simple Array – Descending

The example below demonstrates the use of Utils::sortBy to sort a simple array.

In this example, a sorting condition (comparison function) is specified. In this case, the array is sorted in descending order.

Note: In the example below, a lambda is used, though it is not required. A regular function can be used here as well.


3. Object Vector – Multi Key Sort

The example below demonstrates the use of Utils::sortBy to sort an object vector.

In this example, multiple sorting conditions (comparison functions) are specified. In this case, the vector is sorted by multiple object properties.

When multiple sorting conditions are specified, the sequence is sorted in the order in which the conditions are supplied (FIFO).

Note: In the example below, lambda functions are used, though they are not required. Regular functions can be used here as well.


4. Utils Namespace

The following is the Utils Namespace. Include this in your project to start using!


5. More Examples

Below are more examples demonstrating the use of the ‘Utils‘ Namespace. Don’t forget to include the module when running the examples!

QUICK NOTES:
The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

Was this article helpful?
👍 YesNo

Leave a Reply