c ++配列付きのキューを実装する

キュー(待ち行列)の特徴である:
FIFO

配列の実装:
配列:要素の格納
i:要素を格納する次のエンキューの位置のインデックス
j:要素を削除する次のデキューの位置の次の表
サイズ:キューの最大長
num:キュー内の要素

#include <iostream>
using namespace std;
template<typename T>
class queue{
    public: 
        queue(int size=0){
            array = new T[size];
            i = 0;
            j = 0;
            num = 0;
            this->size = size;
        }
        void push(T val){
            if(num < size && i < size - 1){
                array[i] = val;
                i++;
                num++;
            }else if(num < size && i == size - 1){
                array[0] = val;
                i = 1;
            }
        }
        void pop(){
            if(j == size - 1){
                j = 0;
            }else{
                j++;
            }
            num--;
        }
        int size(){
            return num;
        }
        int capacity(){
            return size;
        }
        T front(){
            return array[j]; 
        }
        ~queue(){
            delete[] array;
        }
    protected:
        T *array;
        int i;
        int j;
        int size;
        int num;
};
int main(){
    queue<int> q(20);
    q.push(21);
    cout << q.front() << endl;
    q.push(31);
    cout << q.front() << endl;
    q.push(41);
    q.pop();
    cout << q.front() << endl;
    return 0;
}
21件のオリジナル記事を掲載 いいね!0 訪問数163

おすすめ

転載: blog.csdn.net/qq_45227330/article/details/105059690