본문 바로가기
Programming

C++에서 sort 명령 사용법

by 느리게 걷는 즐거움 2024. 12. 11.
반응형

C++에서 sort 명령 사용법

C++의 표준 라이브러리는 데이터를 정렬하는 강력한 도구를 제공합니다. 그중에서도 가장 많이 사용되는 것이 바로 <algorithm> 헤더에 포함된 std::sort 함수입니다. 이번 글에서는 std::sort를 사용하는 방법과 다양한 활용 예제를 알아보겠습니다.

 

1. 기본적인 std::sort 사용법

 

std::sort는 주어진 범위의 데이터를 오름차순으로 정렬합니다.
정렬할 범위는 **반복자(iterator)**를 사용하여 지정합니다.

사용법

#include <iostream>
#include <vector>
#include <algorithm> // sort 함수가 포함된 헤더

int main() {
    std::vector<int> numbers = {5, 2, 8, 1, 3};

    // 오름차순 정렬
    std::sort(numbers.begin(), numbers.end());

    // 결과 출력
    for (int num : numbers) {
        std::cout << num << " ";
    }

    return 0;
}

출력 결과

1 2 3 5 8

 

 

2. 내림차순 정렬하기

 

std::sort는 기본적으로 오름차순으로 정렬합니다.
내림차순 정렬을 위해서는 **비교 함수(comparator)**를 제공합니다.

내림차순 정렬 예제

#include <iostream>
#include <vector>
#include <algorithm>

int main() {
    std::vector<int> numbers = {5, 2, 8, 1, 3};

    // 내림차순 정렬
    std::sort(numbers.begin(), numbers.end(), std::greater<int>());

    // 결과 출력
    for (int num : numbers) {
        std::cout << num << " ";
    }

    return 0;
}

출력 결과

8 5 3 2 1

 

 

3. 사용자 정의 비교 함수 사용하기

 

정렬 조건이 복잡하거나 커스텀 정렬이 필요하다면, 직접 비교 함수를 정의할 수 있습니다.
예를 들어, 문자열을 길이 순으로 정렬한다고 가정해 보겠습니다.

문자열 길이로 정렬

#include <iostream>
#include <vector>
#include <algorithm>

bool compareByLength(const std::string& a, const std::string& b) {
    return a.size() < b.size();
}

int main() {
    std::vector<std::string> words = {"apple", "kiwi", "banana", "grape"};

    // 문자열 길이 기준 오름차순 정렬
    std::sort(words.begin(), words.end(), compareByLength);

    // 결과 출력
    for (const std::string& word : words) {
        std::cout << word << " ";
    }

    return 0;
}

출력 결과

kiwi grape apple banana

 

 

4. 구조체 또는 클래스 정렬

객체를 정렬할 때도 std::sort를 활용할 수 있습니다.
예를 들어, 학생들의 이름과 점수를 정렬한다고 가정해 보겠습니다.

구조체 정렬 예제

#include <iostream>
#include <vector>
#include <algorithm>
#include <string>

struct Student {
    std::string name;
    int score;
};

// 점수 기준 오름차순 정렬
bool compareByScore(const Student& a, const Student& b) {
    return a.score < b.score;
}

int main() {
    std::vector<Student> students = {
        {"Alice", 85},
        {"Bob", 90},
        {"Charlie", 75},
        {"Dave", 95}
    };

    // 점수 기준 정렬
    std::sort(students.begin(), students.end(), compareByScore);

    // 결과 출력
    for (const Student& student : students) {
        std::cout << student.name << " (" << student.score << ")\n";
    }

    return 0;
}

출력 결과

Charlie (75)
Alice (85)
Bob (90)
Dave (95)

 

 

5. std::sort와 std::stable_sort의 차이점

 

std::sort는 불안정 정렬(unstable sort) 알고리즘을 사용합니다.
즉, 정렬 기준이 동일한 요소들의 상대적인 순서가 보장되지 않습니다.
만약 이러한 순서를 유지해야 한다면, std::stable_sort를 사용하세요.

#include <algorithm> // stable_sort가 포함된 헤더

 

 

6. 정리

 

std::sort는 다음과 같은 특징을 가집니다:

  • 시간 복잡도: 평균 O(Nlog⁡N)O(N \log N)
  • 정렬 기준: 기본 오름차순, 또는 사용자 정의 가능
  • 범위 지정: 반복자(iterator)로 시작과 끝을 정의

이 함수를 잘 활용하면 데이터를 효율적으로 정렬할 수 있습니다.

 

반응형