Passing Array from Struct to Function

Hi,
I have a stuct that includes values of 4 different assighnments completed by 50 students.
I am trying to find the mean value for each of these assighnments and implement this code in a function rather than re-writing the code 4 times.
1
2
3
4
5
6
7
8
9
10

double sum, mean;
for(int i = 0; i < list_size; i++)
{
        sum += student[i].ass1; 
}	
	
mean = sum / size;
cout << "Mean: " << mean << endl; 

This code is from main, I am not sure how to turn it into a universal function that will also serve ass2, ass3 and ass4.

1
2
3
4
5
6
7
8
9

struct Record
{
double ass1;
double ass2;
double ass3;
double ass4;
}marks[50];


Thanks for any wisdom.
There are always multiple approaches.

One is to calculate average(s) for the Record simultaneously.
1
2
3
4
5
6
7
Record sum { 0, 0, 0, 0 };
for ( int i = 0; i < N; ++i ) {
  sum.ass1 += marks[i].ass1;
  sum.ass2 += marks[i].ass2;
  // ...
}
Record mean = ...

If the struct had operators += and /, then one could write:
1
2
3
  sum += marks[i];
}
Record mean = sum / N;


Or a use of functor. See http://www.cprogramming.com/tutorial/functors-function-objects-in-c++.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
double get1( const Record & obj ) {
  return obj.ass1
}

double mean( const Record array[], int size, double (*func)(const Record &) ) {
  double sum { 0 };
  for ( int i = 0; i < N; ++i ) {
    sum += func( marks[i] );
  }
  return ( 0 < size ) ? sum / size : 0.0;
}


// used in
double mean1 = mean( marks, 50, get1 );
double mean2 = mean( marks, 50, get2 );

The standard library providers adaptors that can create such "access member" functors (get1, get2, get3 ..).
Last edited on
Topic archived. No new replies allowed.