C++에서 커스텀한 구조체를 형성하기 위해 class와 struct를 씁니다. 하지만 struct만 알아도 충분함
구조체(struct) 는 다음과 같습니다.
// 1) 커스텀한 정렬이 필요할 경우
struct Point{
int y, x;
Point(int y, int x) : y(y), x(x){}
Point(){y = -1; x = -1; }
bool operator < (const Point & a) const{
if(x == a.x) return y < a.y;
return x < a.x;
}
};
// 2) 정렬이 필요하지 않을 경우
struct percent{
int x, y;
double w, d, l;
} a[6]; //간단한 struct
커스텀한 무언가를 진행하고 싶다면 구조체를 통해서 해야 합니다. 예를 들어 2차원적인 자료구조는 pair를
사용하면 되지만 x, y, z 등.. 여러가지 인자들이 나오고 커스텀한 솔팅이 필요하다면 역시나 구조체를
사용하는 것이 좋습니다. 정렬이 필요하지 않은 경우 2번처럼 그냥 단순하게 구조체를 설정하면 됩니다.
하지만 정렬, 즉, 커스텀정렬이 필요할 때 1번처럼 해야 합니다.
- 커스텀 솔팅이란 x를 1순위로 오름차순, y를 2순위로 내림차순...이렇게 복잡한 정렬을 말합니다.
예시
#include<bits/stdc++.h>
using namespace std;
struct Point
{
int y, x, z;
Point(int y, int x, int z) : y(y), x(x), z(z) {}
Point() {y = -1; x = -1; z = -1;}
bool operator < (const Point& a) const {
if(x == a.x)
{
if(y == a.y) return z < a.z;
return y > a.y;
}
return x < a.x;
}
};
vector<Point> v;
int main()
{
for(int i = 10; i >= 1; i--)
{
Point a = {i, i, i};
v.push_back(a);
}
sort(v.begin(), v.end()); // 구조체 operator < 정의해서 오름차순으로 정렬됨
for (auto it : v) cout << it.y << " : " << it.x << " : " << it.z << "\n";
return 0;
}
/*
1 : 1 : 1
2 : 2 : 2
3 : 3 : 3
4 : 4 : 4
5 : 5 : 5
6 : 6 : 6
7 : 7 : 7
8 : 8 : 8
9 : 9 : 9
10 : 10 : 10
*/
따로 떼어서 하고 싶다면(따로 외부에서 커스텀 정렬 함수를 정의하면 됨)
#include<bits/stdc++.h>
using namespace std;
struct Point{
int y, x;
};
bool cmp(const Point & a, const Point & b){
return a.x > b.x;
}
vector<Point> v;
int main()
{
for(int i = 10; i >= 1; i--){
v.push_back({i, 10 - i});
}
sort(v.begin(), v.end(), cmp);
for(auto it : v) cout << it.y << " : " << it.x << "\n";
return 0;
}
/*
1 : 9
2 : 8
3 : 7
4 : 6
5 : 5
6 : 4
7 : 3
8 : 2
9 : 1
10 : 0
*/
'알고리즘 > 기본 문법' 카테고리의 다른 글
<알고리즘> 모듈러 연산 (0) | 2022.04.21 |
---|---|
<알고리즘> 최대공약수/최소공배수 (0) | 2022.04.21 |
<알고리즘> 조합(Combination) (0) | 2022.04.21 |
<알고리즘> 순열(permutation) (0) | 2022.04.21 |
<알고리즘> Split (0) | 2022.04.12 |