
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Maximum in Struct Array Using C++
Here we will see how to get max in the struct array. Suppose there is a struct like below is given. We have to find the max element of an array of that struct type.
struct Height{ int feet, inch; };
The idea is straight forward. We will traverse the array, and keep track of the max value of array element in inches. Where value is 12*feet + inch
Example
#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"; }
Output
Max Height: 10 feet and 5 inches
Advertisements