使用 C++ 查找结构数组中的最大值。


我们将详细介绍如何获取结构数组中的最大值。假设有一个如下所示的结构。我们需要找到该结构类型数组的最大元素。

struct Height{
   int feet, inch;
};

思路非常简单。我们将遍历数组,并保留英寸数中的数组元素的最大值。其中值是 12*英尺 + 英寸。

示例

#include<iostream>
#include<algorithm>
using namespace std;
struct Height{
   int feet, inch;
};
int maxHeight(Height h_arr[], int n){
   int index = 0;
   int height = INT_MIN;
   for(int i = 0; i < n; i++){
      int temp = 12 * (h_arr[i].feet) + h_arr[i].inch;
      if(temp > height){
         height = temp;
         index = i;
      }
   }
   return index;
}
int main() {
   Height h_arr[] = {{1,3},{10,5},{6,8},{3,7},{5,9}};
   int n = sizeof(h_arr)/sizeof(h_arr[0]);
   int max_index = maxHeight(h_arr, n);
   cout << "Max Height: " << h_arr[max_index].feet << " feet and " << h_arr[max_index].inch << " inches";
}

输出

Max Height: 10 feet and 5 inches

更新日期:2019-10-30

585 次浏览

开启 职业生涯

完成课程即可获得认证

开始学习
广告
© . All rights reserved.