简体   繁体   中英

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?

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.

   // 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM