vendredi 21 avril 2017

Dynamic array can update to larger size for all data types except strings

I designed a dynamic array with an update function that deep copies the contents of the original into a temp array, then doubles the size then puts the contents of temp array into the new one.

This is the function:

   T& operator[](const unsigned i)
    {
        if(i >= SIZE)
        {
                 T *temp = new T[SIZE];
                for(int i = 0; i< SIZE; ++i)
                {
                    temp[i]=data[i];
                }
                delete[] data;

                SIZE *= 2;

                data = new T[SIZE];
                for(int j = 0; j< SIZE; ++j)
                {
                    data[j]=temp[j];
                }
                delete[] temp;
        }
        return data[i];
    };

This function works with all data types except strings like:

Vector<string> s;
string str1 = "1";
string str2 = "2";
s[0] = str1;
s[1] = str2;
cout<< s[0]<< s[1]<< '\n';

However with ints for example:

Vector<int> in;
for(i = 0; i < 11; i++){
    in[i] = i;
}
for(i = 0; i < 11; i++){
    cout<< "int test"<< '\n';
    cout<< in[i]<< '\n';
}

The update works perfectly fine.

anyone of you know why?

Thank you.

Aucun commentaire:

Enregistrer un commentaire