728x90
이번에는 선생님께서 주신 문제를 풀어보고, 복습하는 개념으로 블로그를 작성했습니다.
#include<iostream>
#include<vector>
#include<string>
#include<algorithm>
using namespace std;
class Person
{
public:int height;
public:int weight;
public:int num;
};
bool Comp(Person a, Person b)
{
if (a.height == b.height)
return a.weight > b.weight;
return a.height < b.height;
}
int n;
cin >> n;
vector<Person> arr(n);
for (int i = 0; i < n; i++)
{
cin >> arr[i].height >> arr[i].weight;
arr[i].num = i + 1;
}
sort(arr.begin(), arr.end(), Comp);
for (auto i : arr)
{
cout << i.height << ' ' << i.weight << ' ' << i.num << endl;
}
}
먼저 Person class를 정의합니다.
class Person
{
public:int height;
public:int weight;
public:int num;
};
그 다음으로 비교 함수를 정의합니다.
bool Comp(Person a, Person b)
{
if (a.height == b.height)
return a.weight > b.weight;
return a.height < b.height;
}
그 다음으로 메인 함수를 정의합니다.
입력 처리 단계입니다.
for (int i = 0; i < n; i++)
{
cin >> arr[i].height >> arr[i].weight;
arr[i].num = i + 1;
}
for 루프를 통해 n개의 Person 객체에 대해 height와 weight를 입력받습니다.
각 객체의 num 멤버 변수는 1부터 시작하는 순서대로 설정됩니다.
다음으로 정렬을 한 뒤, 출력합니다.
sort(arr.begin(), arr.end(), Comp);
for (auto i : arr)
{
cout << i.height << ' ' << i.weight << ' ' << i.num << endl;
}
728x90
'c++ > 학교 문제 풀이' 카테고리의 다른 글
c++ 문제 풀이 - 100일 계산 (0) | 2025.04.25 |
---|---|
c++ 문제 풀이 - 객체의 정렬 1 (0) | 2025.04.24 |
c++ 문제 풀이 - 인내의 숲 2단계 - 2 (0) | 2025.03.28 |
c++ 문제 풀이 - 인내의 숲 2단계 - 1 (0) | 2025.03.27 |
c++ 문제 풀이 - 인내의 숲 1단계 - 2 (0) | 2025.03.26 |