I'm trying to make an ArrayList, an ADT object that uses dynamically allocated arrays to store data. It's supposed to mimic the vector class in that all I want the object to do is:
- store data in a dynamically array
- I want to define a default constructor (but I don't want to define any of the big three if I don't need to, and I don't think I need to)
- have a working size function that returns the current size of the object's array, i.e the size of the list
- an at() function
- an insert(index, value) function
- a remove(index) function
I keep getting leakage errors tho :( I have attached my code for my header file, and a cpp file where I define my member functions. Does anyone think they can take a quick look at my code and tell me what I'm doing wrong?
header file:
#ifndef ARRAYLIST_H
#define ARRAYLIST_H
#include <cstdlib>
// declare class here
class ArrayList{
private:
int listSize;
int* arr;
public:
ArrayList();
int size() const;
int at(int index) const;
void insert(int index, int value);
void remove(int index);
};
#endif // ARRAYLIST_H
#include <stdexcept> //
#include "ArrayList.h"
// define class methods here
ArrayList::ArrayList() {
listSize = 0;
arr = new int[listSize];
}
int ArrayList::size() const{
return listSize;
}
int ArrayList::at(int index) const{
return arr[index];
}
void ArrayList::insert(int index, int value) {
// make a tempArr
// make listSize the listSize+1
// iterate through new tempArr and make it the same as arr until index is reached.
// at index, do tempArr[index] = value;
listSize++;
int* tempArr = new int[listSize];
for(int i = 0; i < listSize; i++){
if(i < index){
tempArr[i] = arr[i];
}
else if(i == index){
tempArr[index] = value;
}
else{
tempArr[i] = arr[i - 1];
}
delete [] arr;
arr = tempArr;
}
}
void ArrayList::remove(int index){
listSize--;
int* tempArr = new int[listSize]; // making a temporary dynamically allocated arr
for(int i = 0; i < listSize; i++){
if(i == index){ // skipping copying this element
continue;
}
tempArr[i] = arr[i];
delete [] arr;
arr = tempArr;
}
}