안녕 세상아,

[c++/struct] 구조체(struct) 정렬하기 (vector 사용) 본문

c++ 개념

[c++/struct] 구조체(struct) 정렬하기 (vector 사용)

돈 많은 백수가 되고싶다 2023. 5. 8. 20:54

구조체를 정렬할 때 벡터로 변환해서 정렬하면 편하다. struct 입력 받는 것도 벡터를 이용해서 받으면 돼서 따로 문법을 외우지 않아도 된다. 역시 벡터가 짱인듯?

하지만 일반적인 벡터와 달리 조건이 있어야한다. 조건 없이 하면 에러가 나면서 작동하지 않는다.

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

struct Person
{
	string name;
	int kor, eng, math;
};

bool compare(Person p1, Person p2) {
	if (p1.kor == p2.kor && p1.eng == p2.eng && p1.math == p2.math)
		return p1.name < p2.name;
	if (p1.kor == p2.kor && p1.eng == p2.eng)
		return p1.math > p2.math;
	if (p1.kor == p2.kor)
		return p1.eng < p2.eng;
	return p1.kor > p2.kor;
}


int main() {
	ios::sync_with_stdio(false);
	cin.tie(NULL);
	cout.tie(NULL);

	int n;
	cin >> n;
	
	vector<Person> persons(n);

	for (int i = 0; i < n; i++) {
		cin >> persons[i].name >> persons[i].kor >> persons[i].eng >> persons[i].math;
	}

	sort(persons.begin(), persons.end(),compare);

	for (int i = 0; i < n; i++) {
		cout << persons[i].name << endl;
	}
}

위와 같이 compare이라는 조건이 있어야지 코드가 정상적으로 작동을 한다.

조건은

  1. 국어 점수 감소하는 순서
  2. 국어 점수 같으면 영어 점수 증가하는 순서
  3. 국어, 영어 점수 같으면 수학 점수 감소하는 순서
  4. 모든 점수 같으면 이름 사전 순으로 증가하는 순서 (아스키코드 순 - 대문자는 소문자보다 작음)

나는 이 문제를 풀면서 큰 실수를 했는데 바로바로 struct와 bool compare를 바꿔서 작성하였다,,역시 당연히 틀렸고 이유를 몰랏음,,ㅋㅋ