使用C ++在结构数组中查找max。
在这里,我们将看到如何在struct数组中获取max。假设有一个类似下面的结构。我们必须找到该结构类型的数组的max元素。
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
热门推荐
10 香港老妈结婚祝福语简短
11 毕业立体贺卡祝福语简短
12 简短新年年会祝福语
13 评论小品祝福语大全简短
14 恭喜师兄结婚祝福语简短
15 员工集体辞职祝福语简短
16 高中新生祝福语 简短
17 装修祝福语男生搞笑简短
18 生日开业蛋糕祝福语简短