finding max array and it's element number

So in our code we have something like this:
1
2
3
4
struct number{
char name[10];
int points[100];
int sum;



Let's say we ran a program, it read a data from txt, did some calculations and the results turned out as

1
2
3
4
5
6
7
  number[1].name=Ted
  number[1].sum=6  
  number[2].name=Bob
  number[2].sum=9

... (and bunch of others with number[i].sum<9)
let's say i=10 





Now how to find the max value without losing it's element number in order to know and print out max sum together with the name it belongs to? In this case output should be

Bob 9


It's getting on my nerves how such a simple things get so complicated in C++.. :D

Isn't there MAX(variable[i]) or some similiar code? No success googling it. And then again, how to know which particular i - name is a calculated max number?

Last edited on
One way to approach this is to loop through your array and compare each sum member to a variable called biggestSoFar or something meaningful like that. When number[ i ]. sum exceeds biggestSoFar, save the index (i in this case) to another variable, and assign this sum to biggestSoFar.

After you finished your loop, you will have the index of the array that contained the largest value of sum.
I suggest using algorithm's max_element with a lambda to compare exactly what you want. Documentation is here http://www.cplusplus.com/reference/algorithm/max_element/

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
struct F
{
    int a;
    char b;
};

#include <algorithm>
#include <ctime>
#include <random>
#include <iostream>

int main()
{
    std::srand(std::time(nullptr));
    F a[100];
    for (int i = 0; i < 100; ++i)
    {
        a[i].a = std::rand();
        a[i].b = std::rand() % 255;
    }

    F *ptr = std::max_element(a, a + 100, [](const F &lhs, const F &rhs){return lhs.a < rhs.a;});
    unsigned index = std::distance(a, ptr);
    std::cout << a[index].a << " with " << a[index].b << " @ index: " << index;
    return 0;
}
Last edited on
Topic archived. No new replies allowed.