We know that if we want to swap the value of two variables, just have a temporary variable to store the value of one of the two and then assign the value of the first to the temporary, the first to the second and the second to the temporary, like this:
If we want to use a function we need to pass it as a pointer or (de)reference, because we need to change the value stored in the memory address, if we don’t use one of these methods, copies of the variables will be created and the values will not be changed, I particularly prefer to use ( de)reference because the implementation is simpler and the performance is the same as using pointers, so our code using function would look like this:
But there is a limitation, as it only changes integer. So we would have to overload the swap() function multiple times for various types, and that’s pretty weird.
So we could use template:
But we don’t need to create this function whenever we want to do this operation, the STL already has this feature, just use it: std::swap:
Always check if there is already a function you want in STL, it is more professional to use it!
Sort values from an array
Suppose you have an array and you want to print the elements in descending order of value, for that you just store the initial value in a variable, compare and do a std::swap, then you would do like this in a nested for loop:
Output: 89 79 52 17 13 12 11 9 8 4 2
If you want otherwise, just change the greater-than sign (>) by the less-than sign (<) in the comparison condition in:
Change this:
For this:
And the values will be printed in ascending order:
Output: 2 4 8 9 11 12 13 17 52 79 89
Well, although this code is good, the truth is that we can improve using the std::greater and std::sort of the STL.
std::sort is a function that sorts the values of an array.
std::greater is a function object that returns the largest value in a comparison.
By default the sort() function sorts the values in ascending order. So if we want to transform the code above using std::sort it would be:
Need to include the #include <algorithm>
Output: 2 4 8 9 11 12 13 17 52 79 89
The std::sort is overloaded, so if we want to print in descending order we need to use the third parameter with std::greater it would be: