Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

หาค่าสูงสุดในอาร์เรย์ Struct ด้วย C++

ที่นี่เราจะดูวิธีหาค่าสูงสุด (Max) ในอาร์เรย์ Struct สมมติมี Struct ด้านล่างนี้ กำหนด เราต้องหาสมาชิกสูงสุดของอาร์เรย์ประเภท Struct นั้น

struct Height {
    int feet, inch;
};

แนวคิดง่ายมาก เราจะท่องอาร์เรย์ และติดตามค่าสูงสุดของสมาชิกอาร์เรย์ในหน่วยนิ้ว โดยค่าคือ 12*feet + inch

ตัวอย่างโค้ด

#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