[참고자료]sort 방법

728x90
  1. sort 사용시 import algorithm
  2. compare 함수에서 return true 시 = 없어야 함 !!
  3. 첫번째 인자가 두번째 인자보다 "strict weak ordering" 관계에 있어서 앞에 있어야 한다면 return true 그게 아니라면 false
    1. For all a, comp(a,a)==false
    2. If comp(a,b)==true then comp(b,a)==false
    3. if comp(a,b)==true and comp(b,c)==true then comp(a,c)==true
#include <algorithm>
#include <queue>

using namespace std;

struct Point{
    int i, j;
};
bool cmp(const int &a, const int &b){
    if (a > b) return true;
    return false;
}

int main() {
    int a[5] = { 2,7,4,4,9 };
    sort(a, a + 5);
    for (int i = 0; i < 5; i++) {
        printf("%d ", a[i]); // 2 4 4 7 9
    }

    printf("\n");
    sort(a, a + 5, cmp);
    for (int i = 0; i < 5; i++) {
        printf("%d ", a[i]);// 9 7 4 4 2
    }
    printf("\n");

    sort(a, a + 5, greater<int>()); // less
    for (int i = 0; i < 5; i++) {
        printf("%d ", a[i]);//9 7 4 4 2
    }
    printf("\n");

    priority_queue<int, vector<int>, greater<int>> pq;
    pq.push(1);
    pq.push(9);
    pq.push(5);

    int first = pq.top();
    printf("%d", first);
    printf("\n");
    return 0;
}
 
priority-queue 사용시, 두번째 인자가 첫번째 인자보다 앞에 있어야한다면 true.
(true 면 swap이 일어난다고 생각하며 됨)
 
struct compare{
	bool operator()(pair<int, int>a, pair<int, int>b){
		return a.second>b.second;
	}
};

int main(){
	priority_queue<pair<int, int>, vector<pair<int, int>>, compare>pq;
	pq.push({1, 10});
	pq.push({2, 3});
	pq.push({3, 1});
	cout<<pq.top().first; // 출력 : 3
	cout<<pq.top().second; // 출력 : 1
}

 

728x90

'풀이기록' 카테고리의 다른 글

[백준 C++] 9663번: N-Queen  (0) 2022.07.10
[백준 C++]1103번: 게임  (0) 2022.07.10
[백준 C++]7453번: 합이 0인 네 정수  (0) 2022.07.09
[참고자료]알고리즘 결정하기  (0) 2022.07.09
[백준 C++] 2805번: 나무자르기  (0) 2022.07.05