Sort()의 기본적인 형태

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

bool comp(int a, int b) {
	return a > b;
}

int main() {

    vector<int> v = {5, 2, 1, 4, 3, 0};

    // default : 오름차순
	sort(v.begin(), v.end());
    for (int i = 0; i < v.size(); ++i)
    	printf("%d ", v[i]);
    printf("\n");

    // 내림차순
    sort(v.begin(), v.end(), comp);
    for (int i = 0; i < v.size(); ++i)
    	printf("%d ", v[i]);
    printf("\n");

    return 0;
}
/*
실행결과
0 1 2 3 4 5
5 4 3 2 1 0
*/

 

이전 포스팅에서 살펴본 Priority Queue의 Compare와 반대이다.

 

즉, comp(a, b)에서 true를 반환할 때의 a가 "strong" order가 되어 우선순위가 높다고 생각하면 될 것 같다.

 

 

Ref.

https://www.cplusplus.com/reference/algorithm/sort/

'Language > C++' 카테고리의 다른 글

[C++] Priority Queue에서의 Compare  (0) 2021.10.11

+ Recent posts