우선순위 큐 구현

C++Beginner
지금 연습하기

소개

이 랩에서는 C++ 프로그래밍 언어의 우선순위 큐 (Priority Queue) 의 기본적인 기능에 대해 배우겠습니다. 우선순위 큐는 C++ STL (Standard Template Library) 의 컨테이너로, 우선순위에 따라 요소를 삽입하고 제거할 수 있습니다. 가장 높은 우선순위를 가진 요소는 항상 큐의 맨 앞에 위치합니다. 큐에서 요소가 제거되면 우선순위 큐는 자동으로 다음으로 높은 우선순위의 요소를 올바른 위치에 삽입합니다.

필요한 라이브러리 포함

다음 명령을 사용하여 ~/project 디렉토리에 main.cpp라는 새 파일을 생성합니다.

touch ~/project/main.cpp

프로그램이 제대로 작동하려면 먼저 필요한 라이브러리를 포함해야 합니다. 이 프로그램에서는 iostreambits/stdc++.h 라이브러리를 사용합니다.

#include <iostream>
#include <bits/stdc++.h>
using namespace std;

show 함수 정의

show 함수는 우선순위 큐에 있는 모든 요소를 표시하는 데 사용됩니다. 이 함수는 우선순위 큐 객체를 인수로 받아서, 원래의 우선순위 큐를 유지하기 위해 큐를 다른 큐로 복사합니다. 그런 다음, 우선순위 큐에 있는 모든 요소를 반복하여 출력합니다.

void show(priority_queue<int> q)
{
    priority_queue<int> pq = q;
    while (!pq.empty())
    {
        cout << "\t" << pq.top(); //printing the top most element
        pq.pop();                 //deleting the top most element to move to the next
    }
    cout << endl;
}

메인 함수 구현

main 함수는 모든 작업이 수행되는 곳입니다. 먼저 정수 변수 i를 선언합니다. 그런 다음 정수 우선순위 큐 q를 생성합니다. push 함수를 사용하여 우선순위 큐에 몇 개의 정수를 추가합니다.

그 후, show 함수를 사용하여 우선순위 큐에 있는 요소를 표시합니다. size 함수를 사용하여 큐에 있는 요소의 수를 표시하고, top 함수를 사용하여 가장 높은 우선순위의 요소를 표시합니다.

다음으로, pop 함수를 사용하여 가장 높은 우선순위의 요소를 제거하고, show 함수를 사용하여 업데이트된 우선순위 큐를 표시합니다.

int main()
{
    priority_queue<int> q;

    for (int i = 1; i < 6; i++)
    {
        q.push(i * 10);
    }

    cout << "The Priority Queue is: ";
    show(q);

    cout << "\n\nThe number of elements in the Priority Queue are: " << q.size();

    cout << "\n\nThe element with the highest priority is: " << q.top();

    q.pop();
    cout << "\n\nAfter Deleting the top most element, Priority Queue becomes: ";
    show(q);

    return 0;
}

최종 코드

C++ 에서 우선순위 큐를 구현하려면 다음 코드를 사용할 수 있습니다.

#include <iostream>
#include <bits/stdc++.h>

using namespace std;

void show(priority_queue<int> q)
{
    priority_queue<int> pq = q;
    while (!pq.empty())
    {
        cout << "\t" << pq.top();
        pq.pop();
    }
    cout << endl;
}

int main()
{
    priority_queue<int> q;

    for (int i = 1; i < 6; i++)
    {
        q.push(i * 10);
    }

    cout << "The Priority Queue is: ";
    show(q);

    cout << "\n\nThe number of elements in the Priority Queue are: " << q.size();

    cout << "\n\nThe element with the highest priority is: " << q.top();

    q.pop();
    cout << "\n\nAfter Deleting the top most element, Priority Queue becomes: ";
    show(q);

    return 0;
}

위 코드를 ~/project/main.cpp에 저장합니다. 이 코드를 컴파일하고 실행하려면 다음 명령을 사용하십시오.

g++ main.cpp -o main && ./main

요약

이 랩에서는 C++ 에서 우선순위 큐의 기본 개념에 대해 배웠습니다. 또한 우선순위 큐를 선언하고 초기화하는 방법과, 요소의 추가, 제거 및 표시 방법을 살펴보았습니다. 이 튜토리얼이 유용했기를 바랍니다.