[C++ 构造函数设置优先队列 和 限制优先队列]

    xiaoxiao2021-11-30  26

    设计一个固定大小的队列类

    #include <iostream> #include <queue> using namespace std; template<class T, class Cont = vector<T>, class Pred = less<Cont::value_type> > class FixedPriority :public priority_queue<T, Cont, Pred> { int nLimit; public: FixedPriority(int nLimit) //通过构造函数设置优先队列大小 { this->nLimit = nLimit; } void SetLimitSize(int nLimit)//或通过函数设置优先队列大小 { this->nLimit = nLimit; } bool Push(T& t) { if (nLimit > size()) { push(t); return true; } return false; } }; void main()//测试 { FixedPriority<int> fp(10);//大小为10个元素的优先队列 for (int i = 0; i<15; i++)//准备压入15个元素 { if (!fp.Push(i)) { cout << "优先队列已满,第" << i << "个元素没有插入" << endl;//后5个元素没有压入 } } cout << endl; cout << "打印队列内容:" << endl; while (!fp.empty()) { cout << fp.top() << "\t"; fp.pop(); } system("pause"); }
    转载请注明原文地址: https://ju.6miu.com/read-679024.html

    最新回复(0)