除了标准的顺序容器外,STL还提供了3种容器适配器,queue,priority_queue和stack
适配器是对顺序容器的包装,它的作用是简化接口.
queue接口十分的简单,只有8个方法。再加上构造函数和比较运算符,push()和emplace()
在queue末尾添加元素。Pop()从头部移除元素。通过front()和back()可以返回头部和尾部元素的引用;切记:pop()不会返回一个元素的副本,如果需要这个pop()的元素,这在之前调用front()方法;
在PacketBuffer.h文件里:
#ifndef QUEUE_PACKETBUFFER_H #define QUEUE_PACKETBUFFER_H #include <queue> template<typename T> class PacketBuffer { public: PacketBuffer(int maxSize = 0); bool packetBuffer(const T& packet); T getNextPacket(); private: std::queue<T> mPackets; int mMaxSize; }; #endif //QUEUE_PACKETBUFFER_H
在PacketBuffer.cpp文件里:
// // Created by Administrator on 2019/2/18. // #include <stdexcept> #include "PacketBuffer.h" template<typename T> PacketBuffer<T>::PacketBuffer(int maxSize) :mMaxSize(maxSize) { } template<typename T> bool PacketBuffer<T>::packetBuffer(const T& packet) { if(mMaxSize > 0 && mPackets.size() == mMaxSize) { return false; } mPackets.push(packet); return true; } template<typename T> T PacketBuffer<T>::getNextPacket() { if(mPackets.empty()) { throw std::out_of_range("packet is empty "); } T temp = mPackets.front(); mPackets.pop(); return temp; }
在main里:
#include <iostream> #include "PacketBuffer.h" #include "PacketBuffer.cpp" class IPPacket { public: IPPacket(int id) :mId(id) { } int getId() { return mId; } private: int mId; }; int main() { PacketBuffer<IPPacket> packet(3); for(int i = 1;i <= 4;++i) { if(!packet.packetBuffer(IPPacket(i))) { std::cout << "Packet " << i << " dropped (queue is full)" << std::endl; } } while(true) { try { IPPacket ipage = packet.getNextPacket(); std::cout << "id :" << ipage.getId() << std::endl; }catch (const std::out_of_range&) { std::cout << "out of range!" << std::endl; break; } } return 0; }
结果是:
Packet 4 dropped (queue is full)
id :1
id :2
id :3
out of range!