💡 퀵 접속: cpp.kr/make_heap

make_heap

C++ 표준 라이브러리의 알고리즘으로, 주어진 범위의 요소들을 힙으로 재배열합니다. 기본적으로 최대 힙을 생성하며, 커스텀 비교 함수를 사용하여 다른 힙 기준으로도 생성할 수 있습니다.

기본 사용법

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

int main() {
    std::vector<int> v = {3, 1, 4, 1, 5, 9, 2, 6};
    
    // 벡터를 힙으로 변환
    std::make_heap(v.begin(), v.end());
    
    // 힙의 최대 요소 출력
    std::cout << "힙의 최대 요소: " << v.front() << std::endl;
    
    // 전체 힙 출력
    std::cout << "힙의 모든 요소: ";
    for (int x : v) {
        std::cout << x << " ";
    }
    std::cout << std::endl;
    
    return 0;
}

실행 결과:

힙의 최대 요소: 9
힙의 모든 요소: 9 6 4 3 5 1 2 1

커스텀 비교 함수 사용

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

int main() {
    std::vector<int> v = {3, 1, 4, 1, 5, 9, 2, 6};
    
    // 벡터를 최소 힙으로 변환
    std::make_heap(v.begin(), v.end(), std::greater<int>());
    
    // 힙의 최소 요소 출력
    std::cout << "최소 힙의 최소 요소: " << v.front() << std::endl;
    
    // 전체 힙 출력
    std::cout << "최소 힙의 모든 요소: ";
    for (int x : v) {
        std::cout << x << " ";
    }
    std::cout << std::endl;
    
    return 0;
}

실행 결과:

최소 힙의 최소 요소: 1
최소 힙의 모든 요소: 1 1 2 3 5 9 4 6

사용자 정의 타입에서 사용

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

struct Person {
    std::string name;
    int age;
    
    bool operator<(const Person& other) const {
        return age < other.age;
    }
};

int main() {
    std::vector<Person> people = {
        {"Alice", 20},
        {"Bob", 25},
        {"Charlie", 30},
        {"David", 15},
        {"Eve", 35}
    };
    
    // 나이 기준으로 힙 생성
    std::make_heap(people.begin(), people.end());
    
    // 힙의 최대 요소(가장 나이 많은 사람) 출력
    std::cout << "가장 나이 많은 사람: " << people.front().name 
              << " (" << people.front().age << "세)" << std::endl;
    
    // 전체 힙 출력
    std::cout << "모든 사람 (나이 순): ";
    for (const auto& person : people) {
        std::cout << person.name << "(" << person.age << "세) ";
    }
    std::cout << std::endl;
    
    return 0;
}

실행 결과:

가장 나이 많은 사람: Eve (35세)
모든 사람 (나이 순): Eve(35세) Bob(25세) Charlie(30세) David(15세) Alice(20세)

참고사항

  • make_heap은 algorithm 헤더에 정의되어 있습니다.
  • 기본적으로 < 연산자를 사용하여 비교합니다 (최대 힙).
  • 커스텀 비교 함수를 제공할 수 있습니다.
  • 시간 복잡도는 O(n)입니다 (n은 범위의 크기).
  • 힙의 최대/최소 요소는 항상 첫 번째 위치에 있습니다.
  • 힙에 새 요소를 추가하려면 push_heap을 사용하세요.
  • 힙에서 최대/최소 요소를 제거하려면 pop_heap을 사용하세요.
함수 설명
make_heap(first, last) 기본 비교 연산자를 사용하여 범위를 힙으로 변환
make_heap(first, last, comp) 커스텀 비교 함수를 사용하여 범위를 힙으로 변환