본문 바로가기
프로그래밍/C & C++

c++로 작성한 간단한 multi level queue

by 체리 2022. 1. 8.
반응형

표준 lib을 써서..

 

#include <iostream>
#include <map>
#include <queue>
#include <memory>
#include <memory>

using namespace std;

template<class Item, class PriorityEnum>
class MultiLevelQueue
{
public:
    MultiLevelQueue(void)
    {
    }

    virtual ~MultiLevelQueue(void)
    {
    }

    void Push(PriorityEnum p, shared_ptr<Item> entry)
    {
        queue_[p].push(entry);
    }

    shared_ptr<Item> Pop(void)
    {
        for (auto& q : queue_)
        {
            if (q.second.size())
            {
                auto item = q.second.front();
                q.second.pop();
                return item;
            }
        }

        return shared_ptr<Item>(nullptr);
    }

    size_t Size(PriorityEnum p)
    {
        return queue_[p].size();
    }

private:
    map<PriorityEnum, queue<shared_ptr<Item>>> queue_;
};

enum class Priority
{
    TopPriority = 0,
    Level_0 = TopPriority,
    Level_1,
    Level_2,
    MAX
};

class Entry
{
public:
    Entry(void)
    {
    }
};

void PrintCount(MultiLevelQueue<Entry, Priority> queue)
{
    for (int i = 0; i < (int)Priority::MAX; ++i)
    {
        cout << i << ": " << queue.Size((Priority)i) << endl;
    }
}

int main()
{
    MultiLevelQueue<Entry, Priority> queue;

    auto i = queue.Pop();
    if (i == nullptr)
        cout << "null" << endl;

    cout << "push level 0 item" << endl;
    queue.Push(Priority::Level_0, make_shared<Entry>());
    PrintCount(queue);

    cout << "push level 1 item" << endl;
    queue.Push(Priority::Level_1, make_shared<Entry>());
    PrintCount(queue);

    cout << "pop" << endl;
    queue.Pop();
    PrintCount(queue);

    cout << "pop" << endl;
    queue.Pop();
    PrintCount(queue);

    cout << "pop" << endl;
    i = queue.Pop();
    if (i == nullptr)
        cout << "null" << endl;
    PrintCount(queue);

    cout << "push level 1 item" << endl;
    queue.Push(Priority::Level_1, make_shared<Entry>());
    PrintCount(queue);

    cout << "pop" << endl;
    queue.Pop();
    PrintCount(queue);

    return 0;
}
반응형

댓글0