×

Structure Sorting (By Multiple Rules) in C++

To understand the concept of Structure Sorting (By Multiple Rules) in C++, it is recommended to know the Structures concept in the C++ programming language. Here the scenario is pretty simple. We have t sort the details of five students using the idea of the structure.

Below is the structure template that we are going to use before we commence with coding:

struct Student .
{
    string name; //it will be a given detail
    int mathematics;  //the Marks in math (Given)
    int physics;   //the Marks in Physics (Given)
    int chemistry;   //the Marks in Chemistry (Given)
    int total marks; //the Total marks (To be filled)
    int rank after sorting ;  //display Rank of student (To be filled)
};

To understand the long lines of code, we will start by understanding different concepts of the C++ programming language we have used to build the logic in our program to display the details of the five student use cases in this scenario.

We have std::sort() function concept in C++ programming language. In this structure sorting, structure object qualities or structure object properties that we have given to them will all be made applicable to objects sorted based on the property of that object.

C++ code to demonstrate Structure Sorting (By multiple Rules) in C++

Code

//Here we are writing the code in the  
//C++ program to demonstrate Structure Sorting in C++
#include <bits/stdc++.h> //initializing the library
using namespace std; //utilizing the namespace std
 
struct Student_details
{
    string name; //it is a given detail
    int mathematics; //the marks in mathematics also a (Given) detail
    int physics; //the marks in physics also a (Given) detail
    int chemistry; //the marks in chemistry also a (Given) detail
    int total; //the marks in the total also a (Given) detail
    int rank; //the marks in tital calculated for the rank a caluclted.
};
 
//down the codes are written for hunction for comparing two students //according to given rules
// function starts here
bool compare_Two_Students(Student_details A, Student_details B)
{
    // If total marks are not same then
    // returns true for higher total
    if (A.total != B.total)
        return A.total > B.total;
 
    // If marks in Maths are same then
    // returns true for higher marks
    if (A.mathematics != B.mathematics)
        return A.mathematics > B.mathematics;
 
    if (A.physics != B.physics)
        return A.physics > B.physics;
 
    return (A.chemistry > B.chemistry);
}
 
// it will Fill total marks and ranks of all Students
void compute_Ranks(Student_details A[], int n)
{
    // from here To calculate total marks for all Students
    for (int i = 0; i < n; i++)
        A[i].total = A[i].mathematics + A[i].physics + A[i].chemistry;
 
    //this is the Sort structure array using user defined
    //this is the function compareTwoStudents()
    sort(A, A + 5, compare_Two_Students);
 
    //from here Assigning ranks after sorting
    for (int i = 0; i < n; i++)
        A[i].rank = i + 1;
}
 
// this is the Driver code
int main()
{
    int n = 5;
 
    //here we have an array of structure objects
    Student_details A[n];
 
    // display details of Student 1
    A[0].name = "helo";
    A[0].mathematics = 180;
    A[0].physics = 195;
    A[0].chemistry = 385;
 
    //display details of Student 2
    A[1].name = "Peter";
    A[1].mathematics = 395;
    A[1].physics = 825;
    A[1].chemistry = 299;
 
    //display details of Student 3
    A[2].name = "Galra";
    A[2].mathematics = 395;
    A[2].physics = 285;
    A[2].chemistry = 380;
 
    //display details of Student 4
    A[3].name = "Jobs";
    A[3].mathematics = 280;
    A[3].physics = 270;
    A[3].chemistry = 390;
 
    //display details of Student 5
    A[4].name = "Joshi";
    A[4].mathematics = 380;
    A[4].physics = 380;
    A[4].chemistry = 380;
 
    compute_Ranks(A, n);
 
    //display column names for displaying data
    cout << "Rank"
         << " "
         << "Name"
         << "     ";
    cout << "Maths"
         << " "
         << "Physics"
         << " "
         << "Chemistry";
    cout << " "
         << "Total\n";
  // Display details of Students from here 
    for (int i = 0; i < n; i++) {
        cout << A[i].rank << "    ";
        cout << A[i].name << "      ";
        cout << A[i].mathematics << "     " << A[i].physics << "     "
             << A[i].chemistry << "       ";
        cout << A[i].total << " ";
        cout << "\n"; }
 return 0;}

Output

Rank  Name      Maths  Physics Chemistry  Total
1    Peter      395     825     299       1519 
2    Joshi      380     380     380       1140 
3    Galra      395     285     380       1060 
4    Jobs       280     270     390       940 
5    helo       180     195     385       760

Related Topics

Abstract class in C++

In this article, you will get exposure to an abstract class in C++. We will discuss this topic using some practical examples too. To understand the abstract classes, you should...

6 minutes read.

Virtual base class in C++

Consider in a C++ program, there are 4 classes named class A, class B, class C, and class D. If class B and class c inherit properties from class A....

3 minutes read.

Armstrong number using for loop in C++

What is For Loop? A for loop is a repetitive control structure that allows you to create a loop to execute a specific number of times efficiently. The syntax that can be...

4 minutes read.

Constructor Overloading

The program contains more than one constructor in a class with the same name, and different types of arguments are called constructor overloading. Calling of constructor depends on the number and types...

2 minutes read.

Pointer to Object in C++

What is a pointer? A pointer in C++ is used to point the variable by storing the address of the variable. In C++, to print the address of the variable, we...

4 minutes read.

Difference between Two Sets in C++

The distinction between the two sets is made up of the components that are present in the first set but absent from the second set. The function consistently duplicates the...

3 minutes read.

C++ Continue in for loop

Continue statement: Inside the loop, the continue statement is used to control the loop. C++ utilizes the continue keyword to implement the continue statement, which transfers the program's flow at the start...

4 minutes read.

Malloc() and new in C++

In C ++, malloc () and new are used for the same thing. During runtime, they are used to allocate memory. Malloc () and the new, on the other hand,...

4 minutes read.

Storage Classes in C

Storage Classes in C Storage Classes are used to define the variable and function property. These functionalities include basically the scope, accessibility, and lifetime that help us detect the existence of...

4 minutes read.

Bit Manipulation in C++

The high-level language in which we communicate is not understood by the computer. As a result, there existed a standard mechanism for understanding any instruction sent to the computer. At...

5 minutes read.

Reverse function in C++

The function std::reverse() is included in the standard template library of C++. It takes in a beginning and ending iterator, reversing the order. To use the reverse statement, we need...

2 minutes read.

Pattern programs in C++

In this article, we are going to discuss different pattern programs in C++. Program for Printing * patterns: Right Angle Triangle* pattern #include <iostream> using namespace std; int main() {     int rows;     cout <<...

3 minutes read.

Default Constructor

C++ Default Constructor A default constructor is such constructor which does not take any parameter. A constructor initializes the data member when a class object created. If a programmer does not create any...

2 minutes read.

C++ Range-based For Loop

In C++ language, the range-based for loop was added, which is far superior than the ordinary For loop. The implementation of a range-based for loop doesn't really need much code. It's a...

4 minutes read.

New Operator in C++

Dynamic memory allocation in C++ means manually allocating the memory by the developer duing run-time. The dynamic memory is allocated in the heap section of the RAM, whereas the static...

3 minutes read.

Counting Frequencies of Array Elements in C++

We have an array of integer items with duplicate values, and our objective is to compute the frequencies of the different elements in the array. Methods: Methods that can be used to...

3 minutes read.

C++ Close file

C++ File Handling close() Function A file which is opened while reading or writing in file handling must be closed after performing an action on it. The close() function is used to close...

2 minutes read.

C++ Deque

Definition: Deque or the Doubly ended queue is a data structure or operation performed under queue where insertion and deletion are allowed at both ends. A deque is an ordered collection of...

5 minutes read.

Compile Time Polymorphism in C++

What is Polymorphism? Polymorphism refers to the existence of various forms. Polymorphism can be simply defined as a message's capacity to be presented in multiple forms. One application of polymorphism in...

4 minutes read.

Hierarchical Inheritance

C++ Hierarchical Inheritance Hierarchical inheritance inherits the property of one base class in more than one derived class.   C++ Hierarchical Inheritance Example #include <iostream>   using namespace std;   class Person {       char gender[10];       int age;   public:       void getPerson()       {           cout << "Age: "; cin >> age;           cout << "Gender: "; cin >> gender;       }       void dispPerson()       {           cout << "Age: " << age << endl;           cout << "Gender: " << gender << endl;       }   };   class Employee : public Person {       float salary;   public:       void getEmployee()       {           Person::getPerson();           cout << "Salary: Rs."; cin >> salary;       }       void dispEmployee()       {           Person::dispPerson();           cout << "Salary: Rs." << salary << endl;       }   };   class Student : public Person {       char level[20];   public:       void getStudent()       {           Person::getPerson();           cout << "Class: "; cin >> level;       }       void dispStudent()       {           Person::dispPerson();           cout << "Level: " << level << endl;       }   };   int main()   {       Person per;       Employee emp;       Student stu;       cout << "Student data" << endl;       cout << "Enter data" << endl;       stu.getStudent();       cout << endl << "Displaying data" << endl;       stu.dispPerson();       cout << endl << "Staff Data" << endl;       cout << "Enter data" << endl;       emp.getEmployee();       cout << endl << "Displaying data" << endl;       emp.dispPerson();   } Output: Student data Enter data Age: 10 Gender: f Class: 5 Displaying data Age: 10 Gender: f Employee data Enter data Age:...

1 minute read.