使用 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
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP