C++
[C++] stack, queue, priority_queue 예제
데굴데구르르 림
2023. 6. 22. 17:08
728x90
알고리즘 문제풀때 스택과 큐 그리고 우선순위 큐는 기본적으로 쓸 줄 알아야 하므로..
기본적인 예제를 저장해 놓는다. +겸사겸사 블로그 환기
이미 다 아는 개념이지만
priority_queue, queue, stack 순서대로
(보통 stack을 먼저 하지만. 개인적으로 priority_queue를 먼저 연습해본다고 순서가 이렇게 됐다.)
#include <iostream>
#include <algorithm>
#include <queue>
#include <stack>
using namespace std;
int main() {
int n;
priority_queue<int> pq;
for (int i=0; i<10; i++) {
cin >> n;
pq.push(n);
}
cout << " ===============\n";
while(!pq.empty()) {
cout << pq.top() << "\n";
pq.pop();
}
cout << " ===============\n";
queue<int> q;
for (int i=0; i<10; i++) {
cin >> n;
q.push(n);
}
while(!q.empty()) {
cout << q.front() << "\n";
q.pop();
}
cout << " ===============\n";
stack<int> s;
for (int i=0; i<10; i++) {
cin >> n;
s.push(n);
}
while(!s.empty()) {
cout << s.top() << "\n";
s.pop();
}
}
입력
8 3 4 2 1 9 8 7 4 5
11 25 47 35 21 8 3 4 9 1
100 200 300 800 33 22 7 8 0 10
결과

🟦 유의점
스택은 후입선출이어서 top()
큐는 선입선출이어서 front()
우선순위큐는 우선순위가 높은대루 정렬돼서 들어가기때문에 top()