Reputation: 1069
I have 3 arrays,
int fJump[13], sJump[13], tJump[13];
each one of them has jumps recorded in them. I'm in need to check whether one of them is bigger than max
, to get the biggest value.
So I could make it like this:
for(int i=0;i<n;i++){
if(max<fJump[i]){
max = fJump[i];
}
if(max<sJump[i]){
max = sJump[i];
}
if(max<tJump[i]){
max = tJump[i];
}
}
but sometimes there are a lot more, so writing like this is a headache. Would there be a nicer and quicker solution to do that?
Upvotes: 2
Views: 166
Reputation: 726839
You can use the max_element
function from the standard library instead of writing your own loop:
int max = *std::max_element(fJump, fJump+13);
max = std::max(max, *std::max_element(sJump, sJump+13));
max = std::max(max, *std::max_element(tJump, tJump+13));
You can also use the max
function inside your loop:
for(int i=0;i<n;i++){
max = std::max(max, fJump[i]);
max = std::max(max, sJump[i]);
max = std::max(max, tJump[i]);
}
Upvotes: 11
Reputation: 64253
You can use max_element :
#include <algorithm>
#include <iostream>
int main()
{
int a1[] = { 7,3,1,29,5 };
int a2[] = { 11,12,18,5,4,3 };
int a3[] = { 10,10,11,10 };
std::vector< int > allMax{
*std::max_element( a1, a1+5 ),
*std::max_element( a2, a2+6 ),
*std::max_element( a3, a3+4 ),
};
auto maxOfAll = *std::max_element( allMax.begin(), allMax.end() );
std::cout << maxOfAll << std::endl;
}
Upvotes: 0
Reputation: 14039
int fJump[13], sJump[13], tJump[13];
int * pA[] = { fJump, sJump, tJump };
int l = sizeof(pA)/sizeof(pA[0]);
for(int i = 0; i < 13; ++i)
{
for (int j = 0; j < l; ++j)
{
if(max < pA[j][i])
{
max = pA[j][i];
}
}
}
Upvotes: 2
Reputation: 126867
int * arrs[]={fJump, sJump, tJump};
int max=arrs[0][0];
for(int j=0; j<sizeof(arrs)/sizeof(*arrs); j++)
{
for(int i=0; i<n; i++)
{
if(max<arrs[j][i])
max=arrs[j][i];
}
}
and you can put as many int
pointers as you want in arrs
(as long as they all come from arrays of the same size - namely n
).
Upvotes: 4