Computer >> 컴퓨터 >  >> 프로그램 작성 >> C++

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