fork download
  1. #include<iostream>
  2. using namespace std;
  3. class Student{
  4. double *grades;
  5. int courseNo;
  6. double cgpa;
  7.  
  8. public:
  9. Student(int n, double *g, double cg=0){
  10. courseNo=n;
  11. grades=new double[courseNo];
  12. for(int i=0;i<courseNo;i++){
  13. grades[i]=g[i];
  14. }
  15. if(cg==0){
  16. double sum=0;
  17. for(int i=0;i<courseNo;i++){
  18. sum+=grades[i];
  19. }
  20. cgpa=sum/courseNo;
  21. }else{
  22. cgpa=cg;
  23. }
  24. }
  25.  
  26. //copy constructor
  27. Student(const Student& s){
  28. courseNo=s.courseNo;
  29. grades=new double[courseNo];
  30. for(int i=0;i<courseNo;i++){
  31. grades[i]=s.grades[i];
  32. }
  33. cgpa=s.cgpa;
  34. }
  35. //assign operator
  36. Student& operator=(const Student& s){
  37. if(this!=&s){
  38. delete[] grades;
  39. courseNo=s.courseNo;
  40. grades=new double[courseNo];
  41. for(int i=0;i<courseNo;i++){
  42. grades[i]=s.grades[i];
  43. }
  44. cgpa=s.cgpa;
  45.  
  46. }
  47. return *this;
  48. }
  49.  
  50. //compare operator
  51. bool operator>(Student& s){
  52. return cgpa>s.cgpa;
  53. }
  54.  
  55. friend ostream& operator<<(ostream&, Student&);
  56.  
  57. };
  58. ostream& operator<<(ostream& out, Student& s){
  59. out<<"([";
  60. for(int i=0;i<s.courseNo;i++){
  61. if(i==0)
  62. out<<s.grades[i];
  63. else
  64. out<<", "<<s.grades[i];
  65. }
  66. out<<"], "<<s.cgpa<<")";
  67. return out;
  68. }
  69. int main(){
  70. double g1[] = {2.5, 3.0, 4.0};
  71. double g2[] = {3.5, 3.7, 3.8};
  72. double g3[] = {2.0, 2.5, 3.0};
  73. double g4[] = {3.8, 4.0, 3.9};
  74.  
  75. Student arr[] = {
  76. Student(3, g1),
  77. Student(3, g2),
  78. Student(3, g3),
  79. Student(3, g4)
  80. };
  81.  
  82. int n=4;
  83. for (int i = 0; i < n - 1; i++) {
  84.  
  85. for (int j = 0; j < n - i - 1; j++) {
  86.  
  87. if (arr[j] > arr[j + 1]) {
  88. Student temp = arr[j];
  89.  
  90. arr[j] = arr[j + 1];
  91.  
  92. arr[j + 1] = temp;
  93. }
  94. }
  95. }
  96.  
  97. for(int i=0;i<n;i++){
  98. cout<<arr[i]<<endl;
  99. }
  100.  
  101.  
  102.  
  103. }
  104.  
  105.  
  106.  
Success #stdin #stdout 0.01s 5300KB
stdin
Standard input is empty
stdout
([2, 2.5, 3], 2.5)
([2.5, 3, 4], 3.16667)
([3.5, 3.7, 3.8], 3.66667)
([3.8, 4, 3.9], 3.9)