목차
- sort란
- 그럼 pair/구조체 각자 정렬은 어떻게 하는데
- compair함수 작성법 사용법
- 나이순 정렬 풀이
1. sort(시작점, 목적지, compare 함수 );
정렬문제에서는 총 2가지 정렬이 있다!
- 오름차순 (기본으로 아무것도 안적으면 실행됨)
- 내림차순 (일명 greater<자료형>)
☆참고☆
http://www.cplusplus.com/reference/algorithm/sort/?kw=sort
2. 아니 근데 compare 함수 는 뭡니까? -> pair 또는 구조체 배열 갖고 놀기
예를 들어서
pair<자료형,자료형> 이나 struct 구조체 를 구성하는
요소(원소/구조체에 포함된 변수든 뭐든.. ㅋㅋ)를 내멋대로 정렬하고 싶다!
https://www.acmicpc.net/problem/11651
좌표를 y좌표가 증가하는 순으로,
y좌표가 같으면 x좌표가 증가하는 순서로 정렬
란다.. 이렇게 요소들의 정렬상태를
- 하나는 오름차순
- 다른 하나는 내림차순
이런식으로 하려면 바로 compair 함수 를 사용하는것이다.
3. 아니 그래서 어떻게 작성하라고?
[함수] _compair 함수_는 리턴형이 bool형이다! (일단 오름차순만 적어봄)
(pair/구조체 변수 A, B가 있을때)
이 표기는 외워두자!
- A < B (오름차순)
- A > B (내림차순)
그럼 기본적으로 어떻게 작성해야하는지 보자
1. 1차 컨테이너 오름차순
1
2
3
4
|
bool compare(int a, int b)
{
return a < b;
}
|
2. pair 컨테이너 오름차순
1
2
3
4
5
6
7
|
bool compare(pair<int,int> a, pair<int,int> b)
{
if(a.first != b.first)
return a.first < b.first;
else if(a.first == b.first )
return a.second < b.second;
}
|
cs |
3. 구조체 컨테이너 오름차순
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
typedef struct _Triple{
int one;
int two;
int three;
}Triple;
bool compare(Triple a, Triple b)
{
if(a.one != b.one)
return a.one < b.one;
else if(a.one == b.one )
{
if(a.two != b.two)
return a.two < b.two;
else if(a.two == b.two)
return a.three < b.three
}
}
|
cs |
... 사실 내가 나중에 봤을떄 이해하기 편하라고 써서.. 이해 안되면 ㅈㅅ.
4. 그래서 나이순 정렬은 어떻게 풀었니
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
|
#include <iostream>
#include <vector>
#include <queue>
#include <stack>
#include <string>
#include <algorithm>
using namespace std;
typedef struct AgeName {
int num;
int age;
string name;
}AN;
vector<AgeName> v;
bool cmp(AgeName a, AgeName b)
{
if (a.age == b.age)
return a.num < b.num;
return a.age < b.age;
}
int main()
{
ios::sync_with_stdio(false); cin.tie(NULL);
int N; cin >> N;
for (int i = 0; i < N; i++)
{
int a; string str;cin >> a >> str;
v.push_back({ i,a,str });
}
sort(v.begin(), v.end(), cmp);
for (int i = 0; i < N; i++){
cout << v[i].age << ' ' << v[i].name << '\n';
}
return 0;
}
|
cs |
..너의 잘못을 알아라
이거 처음에 compare 함수 쓸때
a와 b 랑 비교 했었어야 했는데 깜빡하고
a랑 a 똑같은거 비교해서 틀리고 말았다.. 조심해
'PS > 알고리즘' 카테고리의 다른 글
[백준 17466번] N! mod P 모듈러 연산 성질 (0) | 2021.07.02 |
---|---|
[프로그래머스 정렬] (level1) 1번 - K번째 수 (0) | 2021.06.30 |
[프로그래머스 스택/큐] (level2) 2번 - 프린터 (0) | 2021.06.29 |
[프로그래머스 스택/큐] (level2) 1번 - 기능개발 (0) | 2021.06.28 |
[프로그래머스] string 입력 참고 (0) | 2021.06.28 |