Search code examples
c++templatesdynamic-arrays

Conversion from T to unsigned int, possible loss of data


I am trying to build a dynamic array template class, so far everything has been going good until i tried to use a new object instance of type double, it throws an error as such:

Warning C4244 'initializing': conversion from 'T' to 'unsigned int', possible loss of data

and

Error C2108 subscript is not of integral type

my problem hangs in the Vector(T aSize) function

ive had a look around and i can understand these errors but trying to apply the fix doesn't seem to be work, any help would be awesome.

#include "pch.h"
#include <iostream>
#include "Vector.h"

int main()
{
    std::cout << "Hello World!\n"; 

    Vector<int> test = Vector<int>(5);
    Vector<double> test2 = Vector<double>(10);

    test.insert(1, 8);
    test.insert(3, 22);
    test.getPosition(0);
    test.getSize();
    test.print();
    test[2] = 4;
    test[10] = 0;

    test.print();


    test2.insert(0, 50.0);

}
#include <iostream>
#include <string>

using namespace std;

template <class T>
class Vector
{
public:

    Vector();
    Vector(T aSize);
    ~Vector();
    int getSize();
    int getPosition(T position);
    void print() const;
    void insert(T position, T value);
    void resize(int newSize);
    int &operator[](int index);


private:
    T size;
    int vLength;
    T* data;
};

template <class T>
Vector<T>::Vector() 
{
    Vector::Vector(vLength);
}

template <class T>
Vector<T>::~Vector()
{
    delete[] data;
}

template <class T>
Vector<T>::Vector(T aSize)
{
    size = aSize;
    data = new T[size];
    for (T i = 0; i < size; i++)
    {
        data[i] = 0;
    }
}

template <class T>
void Vector<T>::print() const
{
    for (int i = 0; i < size; i++) 
    {
        cout << data[i] << endl;
    }
}

template <class T>
int Vector<T>::getPosition(T position)
{
    return data[position];
}

template <class T>
void Vector<T>::insert(T position, T value)
{
    data[position] = value;

    cout << "value: " << value << " was inserted into position: " << position << endl;
}
template <class T>
int Vector<T>::getSize()
{
    cout << "the array size is: " << size << endl;
    return size;
}

template <class T>
int &Vector<T>::Vector::operator[](int index)
{
    if ((index - 1) > size) {
        resize(index + 1);
    }
    return data[index];
}

template <class T>
void Vector<T>::resize(int newSize)
{
    T *temp;
    temp = new T[newSize];
    for (int i = 0; i < newSize; i++)
    {
        temp[i] = data[i];
    }

    delete[] data;
    data = temp;
    size = newSize;

    cout << "the array was resized to: " << newSize << endl;
}

Solution

  • You should not use the generic type T to set the size of the dynamic array. Also you should not use T to loop through a container. You should use an integral type instead (int, long, etc).