💡 퀵 접속: cpp.kr/sort
C++ 표준 라이브러리의 알고리즘으로, 컨테이너의 요소들을 정렬하는 함수입니다.
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> numbers = {5, 2, 8, 1, 9};
// 오름차순 정렬
std::sort(numbers.begin(), numbers.end());
// 정렬된 결과 출력
std::cout << "오름차순 정렬: ";
for (const auto& num : numbers) {
std::cout << num << " ";
}
std::cout << std::endl;
return 0;
}
실행 결과:
오름차순 정렬: 1 2 5 8 9
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> numbers = {5, 2, 8, 1, 9};
// 내림차순 정렬
std::sort(numbers.begin(), numbers.end(), std::greater<int>());
// 정렬된 결과 출력
std::cout << "내림차순 정렬: ";
for (const auto& num : numbers) {
std::cout << num << " ";
}
std::cout << std::endl;
return 0;
}
실행 결과:
내림차순 정렬: 9 8 5 2 1
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
int main() {
std::vector<std::string> names = {"Alice", "Bob", "Charlie", "David"};
// 문자열 길이로 정렬
std::sort(names.begin(), names.end(),
[](const std::string& a, const std::string& b) {
return a.length() < b.length();
});
// 정렬된 결과 출력
std::cout << "문자열 길이로 정렬:" << std::endl;
for (const auto& name : names) {
std::cout << name << " (" << name.length() << ")" << std::endl;
}
return 0;
}
실행 결과:
문자열 길이로 정렬: Bob (3) Alice (5) David (5) Charlie (7)
| 함수 | 설명 |
|---|---|
| sort(begin, end) | 기본 오름차순 정렬 |
| sort(begin, end, comp) | 커스텀 비교 함수로 정렬 |
| stable_sort() | 안정 정렬 수행 |
| partial_sort() | 부분 정렬 수행 |
| nth_element() | n번째 요소 기준 정렬 |