std::sort takes a RandomIt
(random iterator) as the first and second arguments that must satisfy the requirements of ValueSwappable and LegacyRandomAccessIterator. Instead of using a Plain-Old-Array of int
, you want to use std::array which can then provide the iterators with the member functions .begin()
and .end()
.
Using a proper container from the C++ standard template library makes sorting with std::sort
trivial. You need not even provide a custom compare function to sort in descending order as std::less<int>()
is provided for you (though your purpose may be to provide the compare function)
Your prototype for mycompare
will work fine as is, but preferably the parameters are const type
rather than just type
, e.g.
bool mycompare(const int a, const int b)
{
return a > b;
}
The implementation using the array container is quite trivial. Simply declare/initialize your array a
and then call std::sort (a.begin(), a.end(), mycompare);
A complete working example would be:
#include <iostream>
#include <algorithm>
#include <array>
bool mycompare(const int a, const int b)
{
return a > b;
}
int main (void) {
std::array<int, 7> a = { 5, 4, 3, 1, 2, 6, 7 };
std::sort (a.begin(), a.end(), mycompare);
for (auto& i : a)
std::cout << " " << i;
std::cout << '\n';
}
Example Use/Output
$ ./bin/array_sort
7 6 5 4 3 2 1
Sorting the Plain Old Array*
If you must use a Plain-Old-Array, then you can use plain-old-pointers as your random iterrators. While not a modern C++ approach, you can handle the plain-old-array with std::sort
. You can make use of the builtin std::greater<type>()
for a descending sort or std::less<type>()
for an ascending sort.
An implementation using pointers would simply be:
#include <iostream>
#include <algorithm>
int main (void) {
int a[] = { 5, 4, 3, 1, 2, 6, 7 };
size_t n = sizeof a / sizeof *a;
#if defined (ASCEND)
std::sort (a, a + n, std::less<int>());
#else
std::sort (a, a + n, std::greater<int>());
#endif
for (size_t i = 0; i < n; i++)
std::cout << " " << a[i];
std::cout << '\n';
}
(same output unless -DASCEND
is added as a define on the commandline, and then an ascending sort will result from the use of std::less<int>()
)
Look things over and let me know if you have further questions.