[C/C++] Sort / 첫번째는 오름차순, 두번째는 내림차순

Onam Kwon·2022년 12월 6일
0

C/C++

목록 보기
10/12

Sort / 첫번째는 오름차순, 두번째는 내림차순

  • pair를 이용한 정렬을 할때 오름차순으로 정렬을 하다가 같은값이 나오는 경우가 있다. 이때 두번째 열에도 정렬 조건을 달아주고 싶다면 이런식으로 하면 된다.
    • 아래 예제의 경우에는 첫번째 열은 오름차순, 만약 첫번째 열의 값이 같은 경우가 있다면 두번째 열에서 내림차순으로 정렬한다.

🔽main.cpp🔽

#include <string>
#include <vector>
#include <algorithm>
#include <iostream>

using namespace std;

void printPairVector(vector<pair<int, int>> &v) {
    for(const auto &item: v) {
        cout<<item.first<<","<<item.second<<endl;
    }
}

int comparison(const pair<int,int> &a, const pair<int,int> &b) {
    return a.first < b.first || (a.first == b.first && a.second > b.second);
}

int main() {
    vector<int> first = {1,3,3,2,5};
    vector<pair<int, int>> v;
    for(int i=0;i<first.size();i++) {
        v.push_back(make_pair(first[i], i+1));
    }
    cout<<"Before sorting a vector of pairs: "<<endl;
    printPairVector(v); cout<<endl;
    
    sort(v.begin(), v.end(), comparison);
    cout<<"After sorting a vector of pairs by ascending first element, descending second element: "<<endl;
    printPairVector(v);
    
    return 0;
}

🔽Output🔽

Before sorting a vector of pairs: 
1,1
3,2
3,3
2,4
5,5

After sorting a vector of pairs by ascending first element, descending second element: 
1,1
2,4
3,3
3,2
5,5
  • comparison함수를 통해 첫번째 열에는 오름차순이므로 a.first<b.first를 이용해 점점 커지게 했고, 만약 a와 b가 같다면 두번째 조건인 a.second>b.second를 이용해 내림차순으로 정렬하도록 설정해놨다.

Github

References

profile
권오남 / Onam Kwon

0개의 댓글