C + + implementation of sequential queues

Source: Internet
Author: User

Initialization of sequential queues and operation of queues are saved in queue.h

#ifndef Queue_h#define QUEUE_HTemplate<classT>classqueue{ Public: Queue (intqueuecapacity);BOOLIsempty ();voidFront ();voidRear ();voidPush (T item);voidPop ();PrivateTQueue;intFrontintRearintcapacity;};//using constructors to initialize sequential queuesTemplate<classT>queue<t>::queue (intqueuecapacity) {if(queuecapacity<1)   {Throw "The capacity of the queue must be >0"; }Else{Queue=NewT[queuecapacity];       capacity=queuecapacity; Front=rear=0;//Sacrifice front This position, this position does not put elements}}//element into queueTemplate<classT>voidQueue<t>::P ush (T item) {if((rear+1) {%capacity==front) {Throw "The queue is full"; }Else{rear= (rear+1)%capacity;Queue[Rear]=item; }}//DequeueTemplate<classT>voidQueue<t>::P op () {if(Isempty ())Throw "The queue is empty"; Front= (front+1)%capacity;}//Determine if the queue is emptyTemplate<classT>inline BOOLQueue<t>::isempty () {returnFront==rear; }//Team first elementTemplate<classT>inline voidQueue<t>::front () {if(! Isempty ()) {cout<<"Team first element is"<<Queue[(front+1)%capacity]<<endl; }Else{cout<<"The queue is empty"<<endl; }}//Team tail elementsTemplate<classT>inline voidQueue<t>::rear () {if(! Isempty ()) {cout<<"Team tail element is"<<Queue[rear]<<endl; }Else{cout<<"The queue is empty"<<endl; }}#endif

Main function

#include "queue.h"#include <iostream>Using namespaceSTD;int main () {queue<int> Q (Ten);Q. Push(1);Q. Push(2);Q. Push(3);Q. Front();Q. Rear();Q. Pop();Q. Pop();Q. Pop();Q. Front();Q. Rear();Q. Push(4);Q. Front();Q. Rear();System"Pause");Return0;}

Result diagram

C + + implementation of sequential queues

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.