C++ Algorithm Heap | "힙 알고리즘" 가이드

C++ Algorithm Heap | "힙 알고리즘" 가이드

이 글의 핵심

make_heap·push_heap·pop_heap·sort_heap으로 벡터를 힙으로 다루는 방법, priority_queue와의 관계, 커스텀 비교자, 상위 K개·힙 정렬까지 정리합니다.

힙 알고리즘

힙 자료구조 (최대 힙)

#include <algorithm>
#include <vector>

std::vector<int> v = {3, 1, 4, 1, 5};

// 힙 생성
std::make_heap(v.begin(), v.end());

// 최대값
std::cout << v.front() << std::endl;  // 5

make_heap, push_heap, pop_heap이 하는 일

C++ 표준의 기본 힙은 최대 힙(max-heap) 입니다. 비교 객체가 기본(std::less)일 때, v.front()가 항상 가장 “큰” 원소를 가리킵니다(동률이면 구현에 따라 어느 쪽이든).

연산전제효과복잡도(대략)
make_heap(b, e)없음[b,e)를 힙 구조로 재배열선형
push_heap(b, e)[b,e-1)가 이미 힙, 새 값은 e-1새 원소를 끼워 넣어 다시 힙으로로그
pop_heap(b, e)[b,e)가 힙최상단(최대)을 e-1 위치로 보내고 나머지를 힙으로로그
sort_heap(b, e)[b,e)가 힙전체를 오름차순 정렬(최대 힙 기준)O(n log n)

중요한 사용 순서:

  1. 삽입: v.push_back(x); push_heap(v.begin(), v.end()) — 새 원소가 마지막에 있어야 합니다.
  2. 추출: pop_heap(v.begin(), v.end()); v.pop_back();pop_heap이 “가장 큰 값”을 끝으로 보낸 뒤, 물리적으로 제거는 pop_back으로 합니다.

is_heap, is_heap_until로 디버깅 시 힙 속성이 깨졌는지 확인할 수 있습니다.


priority_queue와의 관계

std::priority_queue는 컨테이너 어댑터로, 내부적으로 보통 vector + push_heap / pop_heap 과 같은 힙 연산을 씁니다. 차이는 인터페이스입니다.

  • priority_queue: push/top/pop만 노출하고, 내부 벡터의 나머지 원소는 캡슐화됩니다. 가장 큰(또는 비교자에 따른 최우선) 하나만 꺼내는 큐로 쓰기 좋습니다.
  • 힙 알고리즘 직접 사용: 같은 vector를 힙 구간과 비힙 구간으로 나누거나, 중간 상태를 직접 순회·수정해야 할 때 유리합니다(예: 힙 일부만 유지, 커스텀 파이프라인).
// 개념적으로 유사: pq.push(3) ≈ v.push_back(3); push_heap(...)
std::priority_queue<int> pq;
std::vector<int> v;

pq.push(3);
v.push_back(3);
std::push_heap(v.begin(), v.end());

최소 힙이 필요하면 priority_queue<int, vector<int>, greater<int>>처럼 비교자를 주면 되고, 아래 커스텀 비교자와 동일한 규칙을 힙 함수들에도 일관되게 적용해야 합니다.


커스텀 비교자(Comparator)와 주의점

make_heap, push_heap, pop_heap, sort_heap은 모두 선택적 Compare 인자를 받습니다. std::priority_queueCompare와 마찬가지로, 힙에서 “가장 앞에 올” 원소가 비교 의미상 “가장 우선”인 쪽이 됩니다.

  • 기본 std::less → 최대 힙(가장 큰 값이 front).
  • std::greater → 최소 힙(가장 작은 값이 front).
std::vector<int> v = {3, 1, 4};
std::make_heap(v.begin(), v.end(), std::greater<>()); // 최소 힙

모든 힙 연산에 동일한 Compare를 넘겨야 합니다. 하나만 다르면 힙 불변식이 깨져 이후 pop_heap 등이 UB입니다.

사용자 정의 타입이면 operator< 또는 람다로 “정렬 기준”을 명확히 하세요.

struct Task { int id; int priority; };

std::vector<Task> tasks = /* ... */;
auto cmp = [](const Task& a, const Task& b) {
    return a.priority < b.priority; // priority 큰 것이 top
};
std::make_heap(tasks.begin(), tasks.end(), cmp);

실전: 상위 K개 찾기 (Top-K)

전체를 정렬하면 O(n log n)이지만, K가 작을 때 크기 K의 힙을 유지하면 O(n log K) 로 줄일 수 있습니다. “가장 큰 K개”를 원하면 최소 힙(가장 작은 값이 루트) 을 K개 유지하고, 더 큰 값이 들어오면 루트를 교체합니다(기존 예시와 동일한 패턴).

  • K ≪ n 이면 전체 정렬보다 유리한 경우가 많습니다.
  • K가 n에 가깝다partial_sortnth_element가 나을 수 있어, 프로파일링으로 선택하세요.
  • 동일 값이 많을 때 순서가 중요하면 stable_sort 등 다른 요구와 맞는지 확인합니다.

힙 정렬(Heap sort) 정리

make_heap으로 최대 힙을 만든 뒤, pop_heap을 반복하면 큰 값부터 뒤로 정렬되고, 결국 sort_heap 한 번으로 오름차순 전체 정렬이 됩니다. 교과서적인 힙 정렬과 동일하며, 실무에서는 보통 std::sort 가 더 빠른 경우가 많아 학습·인터뷰·제약 환경에서 선택하는 경우가 많습니다.

std::vector<int> v = {3, 1, 4, 1, 5, 9, 2, 6};
std::make_heap(v.begin(), v.end());
std::sort_heap(v.begin(), v.end());
// v는 비교자에 따른 정렬 순서(기본은 오름차순)

sort_heap이미 힙인 구간에 대해 동작합니다. 힙이 아닌 벡터에 바로 sort_heap만 호출하면 안 됩니다. 먼저 make_heap이 필요합니다.

기본 사용

#include <algorithm>

std::vector<int> v = {3, 1, 4, 1, 5};

// 힙 생성
std::make_heap(v.begin(), v.end());

// 최대값 제거
std::pop_heap(v.begin(), v.end());
v.pop_back();

// 값 추가
v.push_back(9);
std::push_heap(v.begin(), v.end());

실전 예시

예시 1: 최대 힙

#include <algorithm>
#include <vector>

int main() {
    std::vector<int> heap;
    
    // 요소 추가
    for (int x : {3, 1, 4, 1, 5, 9, 2, 6}) {
        heap.push_back(x);
        std::push_heap(heap.begin(), heap.end());
    }
    
    // 최대값부터 제거
    while (!heap.empty()) {
        std::cout << heap.front() << " ";
        std::pop_heap(heap.begin(), heap.end());
        heap.pop_back();
    }
    // 9 6 5 4 3 2 1 1
}

예시 2: 최소 힙

#include <algorithm>
#include <vector>
#include <functional>

int main() {
    std::vector<int> heap = {3, 1, 4, 1, 5};
    
    // 최소 힙
    std::make_heap(heap.begin(), heap.end(), std::greater<>());
    
    std::cout << "최소: " << heap.front() << std::endl;  // 1
}

예시 3: 상위 k개

#include <algorithm>
#include <vector>

std::vector<int> topK(const std::vector<int>& data, size_t k) {
    std::vector<int> heap;
    
    for (int x : data) {
        if (heap.size() < k) {
            heap.push_back(x);
            std::push_heap(heap.begin(), heap.end(), std::greater<>());
        } else if (x > heap.front()) {
            std::pop_heap(heap.begin(), heap.end(), std::greater<>());
            heap.back() = x;
            std::push_heap(heap.begin(), heap.end(), std::greater<>());
        }
    }
    
    std::sort_heap(heap.begin(), heap.end(), std::greater<>());
    return heap;
}

int main() {
    std::vector<int> data = {3, 1, 4, 1, 5, 9, 2, 6, 5, 3};
    auto top3 = topK(data, 3);
    
    for (int x : top3) {
        std::cout << x << " ";  // 9 6 5
    }
}

예시 4: 힙 정렬

#include <algorithm>

int main() {
    std::vector<int> v = {3, 1, 4, 1, 5, 9, 2, 6};
    
    // 힙 생성
    std::make_heap(v.begin(), v.end());
    
    // 힙 정렬
    std::sort_heap(v.begin(), v.end());
    
    for (int x : v) {
        std::cout << x << " ";  // 1 1 2 3 4 5 6 9
    }
}

힙 연산

// 힙 생성
std::make_heap(begin, end)

// 요소 추가
v.push_back(value);
std::push_heap(begin, end)

// 요소 제거
std::pop_heap(begin, end)
v.pop_back()

// 힙 정렬
std::sort_heap(begin, end)

// 힙 확인
bool isHeap = std::is_heap(begin, end)

자주 발생하는 문제

문제 1: 힙 속성

std::vector<int> v = {3, 1, 4, 1, 5};

// ❌ 힙 아님
// std::pop_heap(v.begin(), v.end());  // 정의되지 않은 동작

// ✅ 힙 생성 후
std::make_heap(v.begin(), v.end());
std::pop_heap(v.begin(), v.end());

문제 2: push_heap 순서

std::vector<int> heap = {3, 1, 4};
std::make_heap(heap.begin(), heap.end());

// ❌ 잘못된 순서
// std::push_heap(heap.begin(), heap.end());
// heap.push_back(5);  // 늦게 추가

// ✅ 올바른 순서
heap.push_back(5);
std::push_heap(heap.begin(), heap.end());

문제 3: pop_heap 순서

std::vector<int> heap = {5, 4, 3, 1, 1};

// ✅ 올바른 순서
std::pop_heap(heap.begin(), heap.end());  // 최대값을 끝으로
heap.pop_back();  // 제거

// ❌ 잘못된 순서
// heap.pop_back();
// std::pop_heap(heap.begin(), heap.end());

문제 4: 비교 함수

// 최대 힙 (기본)
std::make_heap(v.begin(), v.end());

// 최소 힙
std::make_heap(v.begin(), v.end(), std::greater<>());

// 모든 힙 연산에 같은 비교 함수 사용
std::push_heap(v.begin(), v.end(), std::greater<>());
std::pop_heap(v.begin(), v.end(), std::greater<>());

priority_queue vs 힙

// priority_queue: 래퍼
std::priority_queue<int> pq;
pq.push(3);
pq.push(1);
pq.push(4);
std::cout << pq.top() << std::endl;  // 4

// 힙 알고리즘: 직접 제어
std::vector<int> heap;
heap.push_back(3);
std::push_heap(heap.begin(), heap.end());
heap.push_back(1);
std::push_heap(heap.begin(), heap.end());
std::cout << heap.front() << std::endl;  // 4

FAQ

Q1: 힙은?

A: 최대/최소 힙 자료구조.

Q2: make_heap?

A: 벡터를 힙으로 변환.

Q3: push_heap?

A: 힙에 요소 추가.

Q4: pop_heap?

A: 최대값 제거 (끝으로 이동).

Q5: priority_queue?

A: 힙 래퍼. 편리함.

Q6: 학습 리소스는?

A:

  • “Introduction to Algorithms”
  • “Effective STL”
  • cppreference.com

같이 보면 좋은 글 (내부 링크)

이 주제와 연결되는 다른 글입니다.

  • C++ Algorithm Numeric | “수치 알고리즘” 가이드
  • C++ Algorithm Reverse | “역순 알고리즘” 가이드
  • C++ Algorithm Count | “카운트 알고리즘” 가이드

실전 팁

실무에서 바로 적용할 수 있는 팁입니다.

디버깅 팁

  • 문제가 발생하면 먼저 컴파일러 경고를 확인하세요
  • 간단한 테스트 케이스로 문제를 재현하세요

성능 팁

  • 프로파일링 없이 최적화하지 마세요
  • 측정 가능한 지표를 먼저 설정하세요

코드 리뷰 팁

  • 코드 리뷰에서 자주 지적받는 부분을 미리 체크하세요
  • 팀의 코딩 컨벤션을 따르세요

실전 체크리스트

실무에서 이 개념을 적용할 때 확인해야 할 사항입니다.

코드 작성 전

  • 이 기법이 현재 문제를 해결하는 최선의 방법인가?
  • 팀원들이 이 코드를 이해하고 유지보수할 수 있는가?
  • 성능 요구사항을 만족하는가?

코드 작성 중

  • 컴파일러 경고를 모두 해결했는가?
  • 엣지 케이스를 고려했는가?
  • 에러 처리가 적절한가?

코드 리뷰 시

  • 코드의 의도가 명확한가?
  • 테스트 케이스가 충분한가?
  • 문서화가 되어 있는가?

이 체크리스트를 활용하여 실수를 줄이고 코드 품질을 높이세요.


이 글에서 다루는 키워드 (관련 검색어)

C++, algorithm, heap, priority-queue, STL 등으로 검색하시면 이 글이 도움이 됩니다.


관련 글

  • C++ Algorithm Copy |
  • C++ Algorithm Count |
  • C++ Algorithm Generate |
  • C++ 알고리즘 |
  • C++ Algorithm MinMax |