우선 순위 큐는 요소에 "우선 순위"가 첨부 된 컨테이너의 아이디어를 캡처하는 추상 데이터 유형입니다. 우선 순위가 가장 높은 요소는 항상 대기열 맨 앞에 나타납니다. 해당 요소가 제거되면 다음으로 우선 순위가 높은 요소가 앞으로 이동합니다.
C ++ 표준 라이브러리는 다음 작업으로 priority_queue 클래스 템플릿을 정의합니다.
push : 우선 순위 큐에 요소를 삽입합니다.
top : 우선 순위 큐에서 가장 높은 우선 순위 요소를 (제거하지 않고) 반환합니다.
pop : 우선 순위 대기열에서 우선 순위가 가장 높은 요소를 제거합니다.
size : 우선 순위 큐의 요소 수를 반환합니다.
empty : 우선 순위 큐가 비어 있는지 여부에 따라 true 또는 false를 반환합니다.
다음 코드 스 니펫은 정수를 포함 할 수있는 큐와 문자열을 포함 할 수있는 큐, 두 개의 우선 순위 큐를 구성하는 방법을 보여줍니다.
#include <queue>
priority_queue<int> q1;
priority_queue<string> q2;
다음은 우선 순위 대기열 사용의 예입니다.
#include <string>
#include <queue>
#include <iostream>
using namespace std;
int main()
{
piority_queue<string> pq;
pq.push("the quick");
pq.push("fox");
pq.push("jumped over");
pq.push("the lazy dog");
while (!pq.empty()) {
cout << pq.top() << endl;
pq.pop();
}
return 0;
}
이 프로그램의 출력은 다음과 같습니다.
the quick
the lazy dog
jumped over
fox
대기열은 우선 순위 규칙을 따르기 때문에 문자열은 가장 높은 우선 순위에서 가장 낮은 우선 순위로 인쇄됩니다.
때로는 사용자 정의 개체를 포함하기 위해 우선 순위 대기열을 만들어야합니다. 이 경우 우선 순위 대기열은 가장 높은 우선 순위를 갖는 개체를 결정하는 데 사용되는 비교 기준을 알아야합니다. 이는 연산자 ()를 오버로드하는 클래스에 속하는 함수 객체를 통해 수행됩니다. 오버로드 된 ()은 우선 순위를 결정할 목적으로 <역할을합니다. 예를 들어, Time 객체를 저장하기 위해 우선 순위 대기열을 생성한다고 가정합니다. Time 객체에는시, 분, 초의 세 가지 필드가 있습니다.
struct Time {
int h;
int m;
int s;
};
class CompareTime {
public:
bool operator()(Time& t1, Time& t2)
{
if (t1.h < t2.h) return true;
if (t1.h == t2.h && t1.m < t2.m) return true;
if (t1.h == t2.h && t1.m == t2.m && t1.s < t2.s) return true;
return false;
}
}
위의 비교 기준에 따라 시간을 저장하는 우선 순위 대기열은 다음과 같이 정의됩니다.
priority_queue<Time, vector<Time>, CompareTime> pq;
Here is a complete program:
#include <iostream>
#include <queue>
#include <iomanip>
using namespace std;
struct Time {
int h;
int m;
int s;
};
class CompareTime {
public:
bool operator()(Time& t1, Time& t2)
{
if (t1.h < t2.h) return true;
if (t1.h == t2.h && t1.m < t2.m) return true;
if (t1.h == t2.h && t1.m == t2.m && t1.s < t2.s) return true;
return false;
}
};
int main()
{
priority_queue<Time, vector<Time>, CompareTime> pq;
Time t[4] = { {3, 2, 40}, {3, 2, 26}, {5, 16, 13}, {5, 14, 20}};
for (int i = 0; i < 4; ++i)
pq.push(t[i]);
while (! pq.empty()) {
Time t2 = pq.top();
cout << setw(3) << t2.h << " " << setw(3) << t2.m << " " <<
setw(3) << t2.s << endl;
pq.pop();
}
return 0;
}
이 프로그램은 최근 시간부터 가장 빠른 시간까지 인쇄합니다.
5 16 13
5 14 20
3 2 40
3 2 26
가장 빠른 시간에 가장 높은 우선 순위를 지정하려면 다음과 같이 CompareTime을 재정의합니다.
class CompareTime {
public:
bool operator()(Time& t1, Time& t2)
{
if (t2.h < t1.h) return true;
if (t2.h == t1.h && t2.m < t1.m) return true;
if (t2.h == t1.h && t2.m == t1.m && t2.s < t1.s) return true;
return false;
}
};