RnD
RnD

Reputation: 1069

C++, a simpler way to check 3 arrays

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

Answers (5)

Sergey Kalinichenko
Sergey Kalinichenko

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

BЈовић
BЈовић

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

user93353
user93353

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

Debobroto Das
Debobroto Das

Reputation: 862

You can handle it with an array of array of int type.

Upvotes: -3

Matteo Italia
Matteo Italia

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

Related Questions