I need to write an IntArray
implementation for college. I'm wondering if my code could be better and if it is efficient. In the header file are the methods listed that we need to write.
Header file:
#ifndef INTARRAY_H_
#define INTARRAY_H_
#include <iostream>
using namespace std;
class IntArray{
private:
int length;
int * data;
public:
IntArray(int size = 0);
IntArray(const IntArray& other);
IntArray& operator=(const IntArray& original);
int getSize() const { return length; };
int& operator[](unsigned int i);
void resize(unsigned int size);
void insertBefore(int value, int index);
friend ostream& operator<<(ostream& out, const IntArray& list);
~IntArray(){ delete[] data; };
};
#endif
Cpp file:
IntArray::IntArray(int size){
length = size;
data = new int[size];
for(int i = 0;i<size;i++){
data[i] = 0;
}
}
IntArray::IntArray(const IntArray& other){
length = other.length;
data = new int[length];
for(int i =0;i<length;i++){
data[i] = other.data[i];
}
}
IntArray& IntArray::operator=(const IntArray& other){
if(this = &other){
return *this;
}
length = other.length;
data = new int[length];
for(int i = 0; i <length;i++){
data[i] = other[i];
}
return *this;
}
void IntArray::resize(unsigned size){
if (size <= length){
length = size;
return;
}
int * temparr = new int[size];
// copy data
for (int i = 0; i < length; ++i){
temparr[i] = data[i];
}
delete [] data;
data = temparr;
length = size;
}
int& IntArray::operator [](unsigned i){
if(i >= length || i < 0){
throw "index out of bounds";
}
return data[i];
}
void IntArray::insertBefore(int d, int index){
if(index >= length){
throw "index out of bounds";
}
resize(length + 1);
for(int i = length -1;i>index;i--){
data[i] = data[i-1];
}
data[index] = d;
}
resize
doesn't; the copy will happily go out of bounds and a memory leak when you destroy an instance. – ratchet freak Aug 11 at 11:00unsigned
toint
.length
should be changed tounsigned
(all values that can't be negative in the real world should usually beunsigned
). – zenith Aug 11 at 11:02data
isn't freed), out of bound in the assignment one andresize
method.this->
superfluous inoperator[]
. No check for size >= 0. – Armaghast Aug 11 at 13:49