💡 퀵 접속: cpp.kr/sort

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는 algorithm 헤더에 정의되어 있습니다.
  • 기본적으로 오름차순 정렬을 수행합니다.
  • 내림차순 정렬은 greater<T>() 함수 객체를 사용합니다.
  • 커스텀 정렬은 비교 함수나 람다식을 사용할 수 있습니다.
  • 정렬은 불안정 정렬(unstable sort)입니다.
함수 설명
sort(begin, end) 기본 오름차순 정렬
sort(begin, end, comp) 커스텀 비교 함수로 정렬
stable_sort() 안정 정렬 수행
partial_sort() 부분 정렬 수행
nth_element() n번째 요소 기준 정렬