ghkdehddnr20   4년 전

#include <iostream>
#include <algorithm>
#include <string>

using namespace std;

class Student {  // 여러 개의 변수를 하나로 묶기 위해서 사용
                //  즉 하나의 객체를 정의하기 위해 사용
public:
   string name;
   int score;

   Student(string name, int score) {
      this->name = name;
      this->score = score;
   }

// 정렬 기준 정렬 ' 점수가 낮은 순서 -> 오름차순'
   bool operator < (const Student &student)const{  // const를 제거하면 compile error가 나오는데 이유를 모르겠습니다!
      return this->score < student.score;
   }
};

int main(void) {
   Student students[] = {
      Student("잉여인간 1호", 99),
      Student("잉여인간 2호", 92),
      Student("잉여인간 3호", 95),
      Student("잉여인간 4호", 80),
      Student("잉여인간 5호", 89)
   };

   sort(students, students + 5);

   for (int i = 0; i < 5; i++) {
      cout << students[i].name << '\n';
   }
}

djm03178   4년 전

const가 필요한 건 sort 함수가 요구하는 operator<가 const를 요구하기 때문입니다. 요구된 const를 적지 않으면 안 됩니다.

ghkdehddnr20   4년 전

답변 감사합니다!!!

댓글을 작성하려면 로그인해야 합니다.