💡 퀵 접속: cpp.kr/push_heap
C++ 표준 라이브러리의 알고리즘으로, 힙의 마지막 위치에 있는 요소를 힙의 적절한 위치로 이동시킵니다. 기본적으로 최대 힙을 기준으로 하며, 커스텀 비교 함수를 사용하여 다른 힙 기준으로도 동작할 수 있습니다.
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> v = {3, 1, 4, 1, 5};
// 벡터를 힙으로 변환
std::make_heap(v.begin(), v.end());
// 새 요소 추가
v.push_back(9);
// 새 요소를 힙에 추가
std::push_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 5 4 1 1 3
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> v = {3, 1, 4, 1, 5};
// 벡터를 최소 힙으로 변환
std::make_heap(v.begin(), v.end(), std::greater<int>());
// 새 요소 추가
v.push_back(0);
// 새 요소를 최소 힙에 추가
std::push_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;
}
실행 결과:
최소 힙의 최소 요소: 0 최소 힙의 모든 요소: 0 1 1 3 5 4
#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}
};
// 벡터를 힙으로 변환
std::make_heap(people.begin(), people.end());
// 새 사람 추가
people.push_back({"David", 35});
// 새 사람을 힙에 추가
std::push_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;
}
실행 결과:
가장 나이 많은 사람: David (35세) 모든 사람 (나이 순): David(35세) Bob(25세) Charlie(30세) Alice(20세)
| 함수 | 설명 |
|---|---|
| push_heap(first, last) | 기본 비교 연산자를 사용하여 마지막 요소를 힙에 추가 |
| push_heap(first, last, comp) | 커스텀 비교 함수를 사용하여 마지막 요소를 힙에 추가 |