anakin57
anakin57

Reputation: 49

how to find maximum and minimum values of a structure array

I have a structure array of type float:

students[num].height 

which contains 20 values from the program. How can i write a function to find the maximum and minimum values of this structure array?

Upvotes: 1

Views: 4241

Answers (4)

TCS
TCS

Reputation: 5900

Does the structure is being filled via your functions, or do you get it already filled?

If it it is being filled via your functions you can keep 2 variables max (initially set to MIN_INT) and min (initially set to MAX_INT).

For every insert check if the value is bigger than max or smaller than min, if so, set them to properly.

If it is not being filled via your function, I'd go with jonsca's answer.

Upvotes: 1

jonsca
jonsca

Reputation: 10381

Set a float variable max to the height member of the first element of the array, set a float variable min also to the first element's height memeber. Loop over all the structures. As you are looping, if a height is greater than max, set max to that number. If a height is less than min, set min to that height.

Upvotes: 4

Paul Michalik
Paul Michalik

Reputation: 4381

   // student tStudentsArray[20] = ... 
   std::max_element(tStudentsArray, tStudentsArray + tNumberOfStudents,
        [] (const student& pLeft, const student& pRight) {
            return pLeft.height < pRight.height;
        });

..Any C++ class which does not cover the C++ standard library is kind of questionable.

Upvotes: 2

Mahesh
Mahesh

Reputation: 34625

Upvotes: 3

Related Questions