Untitled

mail@pastecode.io avatar
unknown
c_cpp
2 months ago
2.0 kB
6
Indexable
Never
#ifndef QUEUE_H
#define QUEUE_H
#include <iostream>
#include <vector>

template <class T>
class queue
{
public:
    queue();
    typedef std::size_t size_type;
    void push(T);
    void pop();
    T front() const;
    bool empty() const;
    size_type size() const;

private:
    std::vector<T> _v;
    std::size_t _size;
    std::size_t _front;
};

template <class T>
queue<T>::queue(){
    _v;
    _size = 0;
    _front = -1;
}

template <class T>
bool queue<T>::empty() const{
    return (_size == 0);
}

template <class T>
void queue<T>::push(T elem){
    //std::cout << "we are pushing\n";
    if(_size == _v.size()){ //insufficient capacity
        if (_front!=0 && _front!=-1){ //it isn't an exact linear vector
            _v.push_back(0); // add a random element to back of vector
            for (int i = _size; i >= _front; i--){ // shift everything from front position to end one index rightwards
                _v[i] = _v[i-1];
            }
            _v[_front] = elem; // equate what used to be front (and is now tail) to elem
            //std::cout << "element " << _front << "is now = " << elem << std::endl;
            _front++;
        }
        else{
            //std::cout << "else entered\n";
            _v.push_back(elem);
            //std::cout << "this is now the last element: " << _v[_v.size() - 1] << std::endl;
            //std::cout <<"elemnt zero is " << _v[0] << std::endl;
            if (_front == -1) _front = 0;
        }
        _size++;
    }
    else{
        _v[(_front + _size)%_v.size()] = elem;
        _size++;
        //std::cout << "capacity not full\n";
    }
}

template <class T>
void queue<T>::pop(){
    assert(!empty());
    _size--;
    _front = (_front + 1)%_v.size();
}
template <class T>
T queue<T>::front() const{
    return _v[_front];
}

template <class T>
typename queue<T>::size_type queue<T>::size() const{
    return _size;
}



#endif // QUEUE_H
Leave a Comment