Originally Posted by
bengreenwood
Simple question. Say you want to output an array of 5 numbers in order, with the highest first. Would the following be an efficient way to do it, or are there ways to do this better?
For an array of just 5 numbers it does not really matter, but it would probably be both more efficient and clearer to sort the array first then print in the sorted order. For example:
Code:
#include <cstddef>
#include <algorithm>
#include <functional>
#include <iterator>
#include <iostream>
int main()
{
using namespace std;
int scores[] = {33, 99, 74, 89, 12};
const size_t size = sizeof(scores) / sizeof(scores[0]);
// Sort in descending order.
sort(scores, scores + size, greater<int>());
// Print in the sorted order.
copy(scores, scores + size, ostream_iterator<int>(cout, " "));
}
You could of course implement your own sort function if you need to, and use a simple loop to print instead of using std::copy.