💡 퀵 접속: cpp.kr/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(first, last) | 기본 비교 연산자를 사용하여 범위를 힙으로 변환 |
| make_heap(first, last, comp) | 커스텀 비교 함수를 사용하여 범위를 힙으로 변환 |