vector

mail@pastecode.io avatar
unknown
plain_text
2 months ago
1.9 kB
2
Indexable
Never
#include <bits/stdc++.h>

template <typename T>
class vec
{
    int vsize = 0;
    int vcapacity = 0;
    T* array = nullptr;
    public:
    vec(int c=32, int s=0)
    {
        this->vcapacity = c;
        this->vsize = s;
        array = new T[vcapacity];

    }

    void push_back(T el)
    {
        if(size() >= capacity())
        {
            T* a1 = new T[vcapacity*2];
            for(int i=0;i<vcapacity;i++)
                a1[i] = array[i];
            delete [] array;
            array = a1;
            vcapacity *= 2;
        }
        
        array[vsize] = el;
        vsize++;
    }

    int size() const //const pred zagradi vo funkcija znaci deka funkcijata mo\e da se koristi samo za konstanti
    {
        return this->vsize;
    }

    int capacity() const
    {
        return this->vcapacity;
    }

    void display() const
    {
        std::cout<<"Capacity: "<<this->vcapacity<<std::endl;
        std::cout<<"Size: "<<this->vsize<<std::endl;
        for(int i=0;i<this->vsize;i++)
        {
            std::cout<<"["<<i<<"]: "<<array[i]<<"\n";
        }
    }

    int& at(int index)
    {
        index %= vsize; //ova pravi da se loopnuva nizata, za da ne dava greski. primer, index = 200, vsize = 4, pa ke ni go dade element so index 0
        if(index >= vsize)
        {
            return this->array[index];
        }  
    }
    
    T& operator[](unsigned int index) 
    {
        index = index % vsize;
        return this->array[index];
    }

    T pop()
    {
        return array[vsize--];
    }
    ~vec()
    {
        delete [] array;
    }

};


int main()
{
    vec<int> v;
    v.display();
    v.push_back(5);
    v.push_back(10);
    v.push_back(999);

    std::cout<<v[2]<<std::endl;
    //v.at(2) = 4; //ova ke raboti samo deka stavivme & vo funkcijata

    v.display();
    
    return 0;
}
Leave a Comment