※ 이번 문제에서 알게된 점

§  sort(v.begin(), v.end(), custom_func) 함수

 

1. 먼저 vector에 include 되어 있는 pair를 선언해 입력을 받으면 다음과 같다.

vector< pair<int, int> > p;

for (int i = 0; i < num; i++) {
    int n1, n2; cin >> n1 >> n2;
    p.push_back(make_pair(n1, n2));
}

 

 

2. 그 후 sort를 해줘야 하는데, 이때 문제는 sort를 해주면 p.first를 기준으로 정렬 된다는 것.

그래서 사용자가 만든 함수로 sort(v.begin(), v.end(), custom_func) 의 custom_func에 넣어서

p.second 기준으로 정렬되도록 해야한다. 이때, custom_func의 결과값은 0, 1이 나와야 하며 보통 bool type이다.

bool compare(pair<int, int> a, pair<int, int> b) {
    if (a.second == b.second)
        return a.first < b.first;  // a.first가 작으면 true. 즉 작은게 앞에 배치가 된다.
    return a.second < b.second;       // a.second가 더 작으면 true. 즉 작은게 앞에 배치가 된다.
}
sort(p.begin(), p.end(), compare);

 

\

 

 

 

 

 

 

 

§ my solution 

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

bool compare(pair<int, int> a, pair<int, int> b) {
    if (a.second == b.second)
        return a.first < b.first;  // a.first가 작으면 true. 즉 작은게 앞에 배치가 된다.
    return a.second < b.second;       // a.second가 더 작으면 true. 즉 작은게 앞에 배치가 된다.
}

int main() {
    ios_base::sync_with_stdio(0);
    int num; cin >> num;

    vector< pair<int, int> > p;

    for (int i = 0; i < num; i++) {
        int n1, n2; cin >> n1 >> n2;
        p.push_back(make_pair(n1, n2));
    }
    sort(p.begin(), p.end(), compare);

    for (auto x:p) {
        cout << x.first << " " << x.second << '\n';
    }
}

 

 

 

+ Recent posts