Queue buffer : queue « queue stack « C++ Tutorial






#include <queue>
#include <stdexcept>
#include <iostream>
using namespace std;
using std::queue;

template <typename T>

class PacketBuffer{
 public:
  PacketBuffer(int maxSize = -1);

  void bufferPacket(const T& packet);

  T getNextPacket() throw (std::out_of_range);

 protected:
  queue<T> mPackets;
  int mMaxSize;

 private:
  PacketBuffer(const PacketBuffer& src);
  PacketBuffer& operator=(const PacketBuffer& rhs);
};

template <typename T>
PacketBuffer<T>::PacketBuffer(int maxSize)
{
  mMaxSize = maxSize;
}

template <typename T>
void PacketBuffer<T>::bufferPacket(const T& packet)
{
  if (mMaxSize > 0 && mPackets.size() == static_cast<size_t>(mMaxSize)) {
    return;
  }
  mPackets.push(packet);
}

template <typename T>
T PacketBuffer<T>::getNextPacket() throw (std::out_of_range)
{
  if (mPackets.empty()) {
    throw (std::out_of_range("Buffer is empty"));
  }
  // retrieve the head element
  T temp = mPackets.front();
  // pop the head element
  mPackets.pop();
  // return the head element
  return (temp);
}


class IPPacket {};

int main(int argc, char** argv)
{
  PacketBuffer<IPPacket> ipPackets(3);

  ipPackets.bufferPacket(IPPacket());
  ipPackets.bufferPacket(IPPacket());
  ipPackets.bufferPacket(IPPacket());
  ipPackets.bufferPacket(IPPacket());

  while (true) {
    try {
      IPPacket packet = ipPackets.getNextPacket();
    } catch (out_of_range&) {
      cout << "Processed all packets!" << endl;
      break;
    }
  }
  return (0);
}








21.2.queue
21.2.1.Instantiating an STL Queue
21.2.2.Working with a Queue of Integers
21.2.3.A queue for strings: push, empty, front, pop
21.2.4.queue with doubles
21.2.5.queue: push, pop, front and size
21.2.6.queue.front()
21.2.7.Queue buffer
21.2.8.Using a queue to store user-defined object
21.2.9.Queue: push, pop and size