C++/c++
[STL] ์ฐ์ ์์ ํ priority_queue
Rainbow๐Coder
2022. 1. 18. 20:27
728x90
์ฐ์ ์์ ํ priority_queue๋ ํ์ ์๋ ๋ชจ๋ ์์ ์ค์์ ๊ฐ์ฅ ํฐ ๊ฐ์ด Top์ ์ ์งํ๋๋ก, ์ฐ์ ์์๊ฐ ์ค์ ๋์ด ์๋ค. ์ฐ์ ์์ ํ๋ ์๋ฃ๊ตฌ์กฐ Heap์ผ๋ก ๊ตฌํ๋์ด ์์ด pop๊ณผ push๋ฅผ ํ ๋ ๋ง๋ค ์ ๋ ฌ๋๋ค.
priority_queue<int> pq; ์ด๋ ๊ฒ ์ฐ๋ฉด ๋ด๋ฆผ์ฐจ์์ผ๋ก queue์ push๋๊ณ
priority_queue<int, vector<int>, greater<int>> pq; ์ด๋ ๊ฒ ์ฐ๋ฉด ์ค๋ฆ์ฐจ์์ผ๋ก queue์ push๋๋ค.
<๋ฉ์๋>
- push()
- pop() top์ ์์ ์ ๊ฑฐ
- top() ์ฐ์ ์์ ํ์์ top์ ์๋ ์์ ์ฆ ์ฐ์ ์์๊ฐ ๋์ ์์๋ฅผ ๋ฐํ
- empty() ๋น์ด์์ผ๋ฉด true๋ฅผ ๋ฐํํ๊ณ ๊ทธ๋ ์ง ์์ผ๋ฉด false๋ฅผ ๋ฐํ
- size() ์์์ ์๋ฅผ ๋ฐํ
๋ด๋ฆผ์ฐจ์์ผ๋ก queue์ push
#include <iostream>
#include <queue>
using namespace std;
int main() {
priority_queue<int> pq;
pq.push(5);
pq.push(3);
pq.push(2);
pq.push(1);
pq.push(4);
while (!pq.empty()) {
cout << pq.top() << '\n';
pq.pop();
}
return 0;
}
์ถ๋ ฅ
5
4
3
2
1
์ค๋ฆ์ฐจ์์ผ๋ก queue์ push
#include <iostream>
#include <queue>
using namespace std;
int main() {
priority_queue<int, vector<int>, greater<int>> pq;
pq.push(5);
pq.push(3);
pq.push(2);
pq.push(1);
pq.push(4);
while (!pq.empty()) {
cout << pq.top() << '\n';
pq.pop();
}
return 0;
}
์ถ๋ ฅ
1
2
3
4
5728x90