말 그대로 정렬을 도와주는 함수이다.
Sort를 사용하기 위해서는
#include <algorithm>
을 사용해야 한다.
sort(start, end);
sort(start, end, compare);
sort(start, end, greater<type>());
이렇게 3가지가 있다.
1번의 경우 단순히 start 에서 end 범위 내의 값을 오름차순값으로 정리해주는 기능이다.
#include <iostream>
#include <algorithm>
#define MAX 500
using namespace std;
int main() {
int arr[10] = {10,6,5,4,3,5,8,1,7,0};
for (int i = 0; i < 10; i++) {
cout << arr[i] << " ";
}
cout << "\n";
sort(arr, arr+10);
for (int i = 0; i < 10; i++) {
cout << arr[i] << " ";
}
}
이런식으로 정렬해보면
10 6 5 4 3 5 8 1 7 0
0 1 3 4 5 5 6 7 8 10
이렇게 정렬되는것을 볼 수 있다.
다만 신경쓸점은, 시작점 끝점은 arr[0]같은 수가 아니라 arr, arr+10같은 포인터(주소)형태로 넣어야한다는 점이다.
혹은 vector의 경우 vec.begin, vec.end를 사용한다.
compare함수의 결과값을 기준으로 정렬하게 된다.
#include <iostream>
#include <algorithm>
#define MAX 500
using namespace std;
struct Line{
int left;
int right;
};
bool compare(Line a, Line b) {
if (a.left < b.left) return true;
return false;
}
int n;
Line arr[MAX];
int dp[MAX];
int main() {
cin >> n;
fill_n(dp, MAX, 1);
for (int i = 1; i <= n; i++) {
cin >> arr[i].left >> arr[i].right;
}
sort(arr + 1, arr + n + 1, compare);
}
left, right라는 두 값을 Line이라는 구조체를 이용해 받고, 그 값을 left를 기준으로 정렬하는 기능을 구현하는 cpp 코드이다.
만약 a.left가 b.left보다 작다면, 정렬대상에 들어가기에 true를 return하고 정렬된다. 만약 같거나 크다면, false를 반환한다.
혹은
bool icompare(const int &a, const int &b){
if(a > b) return true;
else return false;
}
같은 코드를 통해서 내림차순 정렬을 구현할 수도 있다.
b가 더 작으면 정렬대상이 되니깐 true를 반환하는 식이다.
이 방식은 bool식을 짜기에 따라 무궁무진한 활용법이 있다.
단순히 자료형을 넣으면 내림차순 정렬해주는 예시이다.