기술 블로그

vector struct 구조체 정렬(3개 이상) 본문

C++ STL

vector struct 구조체 정렬(3개 이상)

parkit 2019. 6. 29. 21:06
728x90
반응형

vector struct 구조체 정렬.


cmp 함수를 잘 보자.


참고로 sort의 bool 함수는 하나 하나 다 구현해야한다.



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
43
44
45
46
47
48
49
50
51
52
53
#include <bits/stdc++.h>
 
using namespace std;
 
typedef struct info
{
    int f, t, c;
}info;
 
vector<info> v;
 
bool cmp(const info & a, const info & b)
{
    if (a.f < b.f) return true// 제일 먼저 f를 기준으로 오름차순 정렬
    else if (a.f == b.f) // 만약에 f가 같다면
    {
        if (a.t < b.t) return true// t를 기준으로 오름차순 정렬
        else if (a.t == b.t) // 만약에 t가 같다면
        {
            if (a.c < b.c) return true// c를 기준으로 오름차순 정렬
        }
    }
 
    // 각 경우에 대하여 else를 고려할 필요가 없다.
    return false;
}
 
int main(void)
{
    v = {
        {123},
        {321},
        {114},
        {132},
        {213},
        {320},
        {351},
        {222},
        {111},
        {127},
        {129},
        {331},
        {412},
        {400}
    };
 
    sort(v.begin(), v.end(), cmp);
 
    for (auto i : v)
        printf("\n%d %d %d", i.f, i.t, i.c);
 
    return 0;
}
cs








728x90
반응형

'C++ STL' 카테고리의 다른 글

문자열 자체의 find와 C++ STL인 find  (0) 2019.09.23
search()  (0) 2019.05.20
count(), count_if()  (0) 2019.05.20
equal()  (0) 2019.05.20
is_sorted()  (0) 2019.05.10