I read that blog where a C# programmer show how to use LINQ to extract the 5 top numbers from 3 different Array.
I tried to do the same with C++ and wrote the following, only 5 line of code using vector, and sort. The output is 88 89 110 888 921 as expected.
But have the question is, have you a better solution ?
#include <vector>
#include <iostream>
#include <iterator>
#include <algorithm>
using namespace std;
int main(int argc, char* argv[])
{
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));
copy(begin(max), end(max), ostream_iterator<int>(cout, " "));
return 0;
}
I'd use
boost::zip_iteratorto eleganty append the 3 input arrays, andstd::nth_elementwithstd::greaterto get the 5 largest elements in unspecified orderLive Example.
Complexity: linear
O(N1 + N2 + N3).If you want to have the largest elements in order, you could either use a
std::partial_sortinstead ofstd::nth_elementor do a post-processingstd::sorton the first 5 elements ofv. The complexity ofstd::partial_sortfor the top K elements isO(N log K), which approachesO(N log N)for a full sort. ForK=5, there should be little difference betweenstd::nth_elementandstd::partial_sort.