I am preparing for an interview and came to know about this question: implement a vector class in C++. I thought of how I would write it an interview and included the code below. The things I know I did not cover already are: 1) No use of templates for different data types 2) No use of iterators for iterating. My point is I wanted to write a simple code and I want to know if that would be sufficient to crack the interview round or not? Can you please go through the below code and point out the things that I must cover from an interview perspective. Thanks.
class Vector{
int capacity;
int sizet;
int *arr;
public:
Vector():capacity(0),sizet(0),arr(new int){}
Vector(int size):capacity(size),sizet(size),arr(new int[sizet]()){}
Vector(const Vector &v){ //copy ctor
capacity = v.capacity;
sizet = v.sizet;
arr = new int[sizet];
for(int i=0;i<sizet;i++)
arr[i] = v.arr[i];
}
int &operator [](int index){ //overloading index[] operator
return arr[index];
}
Vector &operator==(const Vector& v){ //overloading assignment operator
if(this != v){
capacity = v.capacity;
sizet = v.sizet;
arr = new int[sizet];
for(int i=0;i<sizet;i++)
arr[i] = v.arr[i];
}
return *this;
}
void push_back(int elem){
if(sizet == capacity){
if(capacity ==0)
capacity++;
else
capacity = 2*capacity;
}
arr[sizet++]=elem;
}
void pop_back(){
sizet--;
}
void insert(iterator it,int size=1,int val=0){
}
int size(){
return sizet;
}
void resize(int n){
if(sizet < n){ //if increasing the size
for(int i=sizet;i<n;i++)
arr[sizet++]=0;
}
else //decreasing the size
sizet = n;
}
int at(int index){
return arr[index];
}
int front(){
return arr[0];
}
int back(){
return arr[sizet];
}
~Vector(){ //dtor
delete arr[];
}
};
Edit: Resolved the naming conflict as was suggested.
Vector::operator[]
return avector&
. Yourinsert
is empty and uses an undefined typeiterator
. You have a data member and a member function sharing the same namesize
. Your destructor is~vector
instead of~Vector
. And there are a lot of compile errors left. \$\endgroup\$