Reputation: 5353
I am attempting to recreate vectors using my own class called MyVector.
template<class T>
class MyVector{
private:
T *v;
int size;
int max;
public:
MyVector();
MyVector(int n);
MyVector(int n, int k);
MyVector(const MyVector &l);
void grow();
MyVector<T>& operator=(const MyVector &lhs);
T &operator[](unsigned int i);
void push_back(T t);
int capacity();
int length();
void reserve (int n);
void resize(int);
};
i am attemping to recreate the push_back()
function that vector has. I understand I need to create a copy of the original array with a size of size+1. but when I try:
template<class T>
void MyVector<T>::push_back(T t) {
MyVector<T> *temp = v;
}
I get the error:
main.cpp: In member function âvoid MyVector<T>::push_back(T) [with T = int]â:
main.cpp:34: instantiated from here
main.cpp:117: error: cannot convert âint*â to âMyVector<int>*â in initialization
I am fairly new to c++, any help is appreciated. thanks!
EDIT My new push_back class
template<class T>
void MyVector<T>::push_back(T t) {
T *temp = v;
v = new T[++size];
temp[size] = t;
for (int i = 0; i < size + 1; ++i){
v[i] = temp[i];
}
delete [] temp;
}
When I call and print the vector in my main program it just appends a 0 to the end of the vector.
Upvotes: 0
Views: 1705
Reputation: 145239
In MyVector<T> *temp = v;
with T
= int
, the v
refers to the data member that has type int*
. You're trying to use that as an initializer for a MyVector*
. Those are pointers to different types, incompatible pointers.
By the way, don't just increase the buffer by 1.
Double its size, or increase by a constant factor, so as to avoid quadratic behavior.
std::vector
guarantees amortized linear time for push_back
.
Upvotes: 4
Reputation: 18443
You are assigning a field of type T*
to a variable of type MyVector<T>*
. That's why you are getting the error. Change the line to:
T *temp = v;
Upvotes: 1