컨테이너의 요소를 정렬하는데 사용되는 알고리즘 함수이다.
std::sort는 빠른 정렬(퀵 정렬, 힙 정렬, 삽입 정렬을 혼합한 하이브리드 정렬 알고리즘)로 구현되어 있으며, 시간 복잡도는 평균적으로 O(n log n)이다.
#include <algorithm>
std::sort(시작_반복자, 끝_반복자, [비교_함수]);
#include <iostream>
#include <algorithm>
#include <vector>
int main() {
std::vector<int> vec = {5, 2, 9, 1, 5, 6};
// 기본 오름차순 정렬
std::sort(vec.begin(), vec.end());
// 출력
for (int num : vec) {
std::cout << num << " ";
}
return 0;
}
std::greater<> 사용)#include <iostream>
#include <algorithm>
#include <vector>
#include <functional> // std::greater 사용 시 필요
int main() {
std::vector<int> vec = {5, 2, 9, 1, 5, 6};
// 내림차순 정렬
std::sort(vec.begin(), vec.end(), std::greater<>());
// 출력
for (int num : vec) {
std::cout << num << " ";
}
return 0;
}
#include <iostream>
#include <algorithm>
#include <vector>
// 짝수를 우선 정렬하는 비교 함수
bool customCompare(int a, int b) {
if (a % 2 == 0 && b % 2 != 0) return true; // 짝수를 우선
if (a % 2 != 0 && b % 2 == 0) return false; // 홀수는 나중
return a < b; // 같은 성격(짝수/홀수)일 경우 오름차순 정렬
}
int main() {
std::vector<int> vec = {5, 2, 9, 1, 5, 6, 8};
// 사용자 정의 비교 함수 사용
std::sort(vec.begin(), vec.end(), customCompare);
// 출력
for (int num : vec) {
std::cout << num << " ";
}
return 0;
}
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
// 문자열 길이를 기준으로 정렬하는 비교 함수
bool lengthCompare(const std::string &a, const std::string &b) {
return a.length() < b.length();
}
int main() {
std::vector<std::string> vec = {"apple", "kiwi", "banana", "grape", "pear"};
// 문자열 길이 기준 정렬
std::sort(vec.begin(), vec.end(), lengthCompare);
// 출력
for (const std::string &str : vec) {
std::cout << str << " ";
}
return 0;
}
#include <iostream>
#include <algorithm>
#include <vector>
int main() {
std::vector<int> vec = {5, 2, 9, 1, 5, 6};
// 람다 함수로 내림차순 정렬
std::sort(vec.begin(), vec.end(), [](int a, int b) {
return a > b;
});
// 출력
for (int num : vec) {
std::cout << num << " ";
}
return 0;
}