Sorting built-in arrays
suggest changeThe sort algorithm sorts a sequence defined by two iterators. This is enough to sort a built-in (also known as c-style) array. std::greater is declared in <functional>.
int arr1[] = {36, 24, 42, 60, 59};
// sort numbers in ascending order
std::sort(std::begin(arr1), std::end(arr1));
// sort numbers in descending order
std::sort(std::begin(arr1), std::end(arr1), std::greater<int>());
Prior to C++11, end of array had to be “calculated” using the size of the array:
// Use a hard-coded number for array size
std::sort(arr1, arr1 + 5);
// Alternatively, use an expression
const std::size_t arr1_size = sizeof(arr1) / sizeof(*arr1);
std::sort(arr1, arr1 + arr1_size);
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents