[STL] Priority_queue 생성, 삽입, 삭제 등 사용법

Notepad96

·

2020. 11. 9. 21:45

300x250

 

 

 

1. priority_queue

 

priority_queue우선순위 큐라고 한다.

 

 

priority_queue는 queue 헤더의 같이 포함되어 있다. 따라서 queue를 include 하였다면 사용할 수 있다.

 

 

 

priority_queue의 인터페이스는 stack과 비슷하여

 

queue에서 사용하였던 frontback은 없고 stack에 있었던 top이 존재한다.

 

 

 

이를 우선순위 큐라고 하는 이유는 각 원소들에 우선순위를 부여하여 이 우선순위에 따라서 우선 처리가 높은 순으로 처리 순서가 정해지기 때문이다.

 

 

 

 

 


2. 코 드

환경 : Visual Studio 2019
 
#include <iostream>
#include <queue>	
using namespace std;

int main() {

	priority_queue<int> pq;	// 기본값 : 오름차순 
	//priority_queue<int, vector<int>, greater<int>> pq; // 내림차순

	if (pq.empty()) {
		cout << "우선 순위 큐가 비어있습니다.\n";
	}

	pq.push(5);	// 5
	pq.push(3);	// 3 5
	pq.push(2);	// 2 3 5
	pq.push(4);	// 2 3 4 5
	pq.push(7);	// 2 3 4 5 7

	cout << "사이즈 : " << pq.size() << "\n";

	while (!pq.empty()) {
		cout << pq.top() << " ";
		pq.pop();
	}
	cout << "\n";

	return 0;
}
 
 
결과
 
 
 

- 여기서 주의할 점은 우선 순위를 생성하였을 시 기본 값인 오름차순으로 우선순위가 지정이 된다.

 
 

따라서 오름차순으로 선언한 우선순위 큐를 while문을 사용하여 top에 값들을 하나 씩 사용한다면

결과에서도 볼 수 있듯이 결국 거꾸로인 내림차순이 되어버린다.

 
 
 

결국 참조하여 값들을 읽을 때는 정렬 방향이 반대가되어버리므로 이러한 점을 주의하여 사용하여야 할 것이다.

 
 
 
 
 


3. 참 조

 

 
 

priority_queue - C++ Reference

container_typeThe second template parameter (Container)Type of the underlying container

www.cplusplus.com

 

 

300x250