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 = { {1, 2, 3}, {3, 2, 1}, {1, 1, 4}, {1, 3, 2}, {2, 1, 3}, {3, 2, 0}, {3, 5, 1}, {2, 2, 2}, {1, 1, 1}, {1, 2, 7}, {1, 2, 9}, {3, 3, 1}, {4, 1, 2}, {4, 0, 0} }; 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
반응형