lundi 16 septembre 2013

C++: Find max top 5 number from 3 array.


Yesterday, I read that blog post where C# developer demonstrate how powerful is LINQ to solve a simple problem.
We have 3 array of Integer  and we want to find the 5 maximum number from those 3 Array.  With LINQ, 7 cascaded operation are enough to do that in 3 line of code.
And I’m wondering how many line I would use in C++ to do the same !
Here is my 1st Draft made in 5min. I use only 5 line of code.
//Headers we need
#include <vector>
#include <iostream>
#include <iterator>
#include <algorithm>

using namespace std;

int Array1 [] = { 9, 65, 87, 89, 888 };
int Array2 [] = { 1, 13, 33, 49, 921 };
int Array3 [] = { 22, 44, 66, 88, 110 };

vector<int> A1(begin(Array1), end(Array1)); 
A1.insert(end(A1), begin(Array2), end(Array2)); 
A1.insert(end(A1), begin(Array3), end(Array3));
sort(begin(A1), end(A1));
vector<int> max(end(A1)-5, end(A1));

//to output the result
copy(begin(max), end(max), ostream_iterator<int>(cout, " "));




But I would see on Stack Overflow if someone has a better solution.

[UPDATE] : you can found interesting to read answer to my StackOverFlow question.
 C++ and C++11 solution are proposed, taking into account the complexity introduce by the sorting. 

Aucun commentaire :

Enregistrer un commentaire