본문 바로가기
C++

[코드트리 객체 정렬] 클래스를 이용한 객체 정렬

by 돌맹96 2024. 9. 13.
728x90
반응형

https://www.codetree.ai/missions/5/problems/korean-english-math-order?&utm_source=clipboard&utm_medium=text

 

코드트리 | 코딩테스트 준비를 위한 알고리즘 정석

국가대표가 만든 코딩 공부의 가이드북 코딩 왕초보부터 꿈의 직장 코테 합격까지, 국가대표가 엄선한 커리큘럼으로 준비해보세요.

www.codetree.ai

 

기본개념 

클래스를 이용한 객체 정렬은 다음과 같이 코드로 정의가 가능하다.

bool cmp(Student a, Student b) { 
    return a.kor < b.kor; 
}

만약 국어 점수가 일치하는 경우 영어점수를 기준으로 오름차순을 정렬한다면 코드는 다음과 같다.

bool cmp(Student a, Student b) { 
    if(a.kor == b.kor)           // 국어 점수가 일치한다면
        return a.eng < b.eng;    // 영어 점수를 기준으로 오름차순 정렬합니다.
    return a.kor < b.kor;        // 국어 점수가 다르다면, 오름차순 정렬합니다.
}

이 방법을 이용하여 국영수 순이지의 코드를 풀어보면 다음과 같다.

#include <iostream>
#include <algorithm>
using namespace std;

class Student
{
    public:
        string name;
        int kor, eng, math;
        Student(){}
        Student(string name, int kor, int eng, int math) {
            this->name = name;
            this->kor = kor;
            this->eng = eng;
            this->math = math;
        }
};

bool cmp(Student a, Student b)
{
    if(a.kor == b.kor)
    {
        if(a.eng == b.eng)
        {
            return a.math > b.math;
        }
        return a.eng > b.eng;
    }    
    return a.kor > b.kor; 
}

int main() {
    int n;
    cin >> n;

    Student student[n];

    for(int i = 0; i < n; i++)
    {
        string name;
        int kor, eng, math;
        cin >> name >> kor >> eng >> math;

        student[i] = Student(name, kor, eng, math);
    }

    sort(student, student + n, cmp);

    for(int i = 0; i < n; i++)
    {
        cout << student[i].name << " " << student[i].kor << " " << student[i].eng << " " << student[i].math << endl;
    }
    return 0;
}
728x90
반응형