C++ Sort() 사용법 및 사용자 정의 함수 compare
‘std::sort()’ 함수는 표준 라이브러리 알고리즘 ‘
#include <algorithm>
#include <vector>
#include <iostream>
bool compare(int a, int b) {
return a > b;
}
int main() {
std::vector<int> v = {4, 1, 3, 5, 2};
std::sort(v.begin(), v.end(), compare);
for(int i : v) {
std::cout << i << ' ';
}
// 출력: 5 4 3 2 1
return 0;
}
‘std::sort()’는 일반적으로 퀵 정렬, 힙 정렬, 삽입 정렬 등의 조합을 사용하는 하이브리드 정렬 알고리즘을 구현한다. 하지만 정확한 구현은 컴파일러에 따라 달라질 수 있으며, 평균 시간 복잡도는 O(n log n)이다.
Enjoy Reading This Article?
Here are some more articles you might like to read next: