Article by Ayman Alheraki on January 11 2026 10:32 AM
Example:
xxxxxxxxxx
using namespace std;
struct Student { string name; int id; array<double, 3> grades;
// Function to print student information void printInfo() const { cout << "Name: " << name << ", ID: " << id << ", Grades: "; for (double grade : grades) { cout << grade << " "; } cout << endl; }};
// Function to calculate the student's GPAdouble calculateGPA(const Student& student) { double sum = 0.0; for (double grade : student.grades) { sum += grade; } return sum / student.grades.size();}
// Function to sort students by GPA in descending ordervoid sortStudentsByGPA(array<Student, 3>& students) { sort(students.begin(), students.end(), [](const Student& a, const Student& b) { return calculateGPA(a) > calculateGPA(b); });}
int main() { array<Student, 3> students = { {"Ali", 123, {85, 92, 78}}, {"Khalid", 456, {90, 88, 95}}, {"Sara", 789, {75, 80, 82}} };
// Print student information before sorting cout << "Before sorting:" << endl; for (const Student& student : students) { student.printInfo(); }
// Sort students by GPA sortStudentsByGPA(students);
// Print student information after sorting cout << "\nAfter sorting:" << endl; for (const Student& student : students) { student.printInfo(); }
return 0;}Explanation:
This C++ code demonstrates how to efficiently manage student data using std::array, a modern C++ container that provides a fixed-size array with bounds checking.
Student Structure: Defines a Student structure to hold student information, including name, ID, and an array of grades.
Functions:
calculateGPA: Calculates the Grade Point Average (GPA) for a given student.
sortStudentsByGPA: Sorts an array of students based on their GPA using the std::sort algorithm and a lambda expression for comparison.
Main Function:
Creates an array of Student objects.
Prints the student information before and after sorting.
Sorts the students based on their GPA using the sortStudentsByGPA function.
Key Features:
std::array: Provides a type-safe and efficient way to work with fixed-size arrays.
std::algorithm: Offers a rich set of algorithms for common operations on containers, such as sorting.
Lambda Expressions: Enable concise and expressive function objects for custom comparisons.
Object-Oriented Programming: The Student structure encapsulates data and behavior.
Advantages of using std::array:
Type Safety: Ensures that only elements of the specified type can be stored in the array.
Efficiency: Often provides better performance than dynamic containers like std::vector for small, fixed-size arrays.
Bounds Checking: Helps prevent out-of-bounds access errors.
This example showcases the power and flexibility of modern C++ features for creating well-structured and efficient data management solutions.