Implement a Template Class MyArray (modify/augment example 12.6):
I'm having issues with my erase() function. What can I do to fix this?
#include <iostream>
#include <cassert>
using namespace std;
class SomeObj{
public:
SomeObj(int d ): id(d){}
int getId() const;
void output();
private:
int id;
};
int SomeObj::getId() const{
return id;
}
void SomeObj::output(){
cout<<id<<endl;
}
template<typename T>
class MyArray {
public:
MyArray();
MyArray(int c);
T& operator[](int index);
void push_back(T e);
int getSize() const;
int getCapacity() const;
int getIndex(T a);
void erase(int index);
private:
void grow();
T *data;
int capacity;
int size;
};
template <typename T>
MyArray<T>::MyArray(): capacity(15), size(0), data(nullptr) {
}
template <typename T>
MyArray<T>::MyArray(int c):capacity(c), size(0) {
assert(c>0);
size = 0;
capacity = c;
data = new T[capacity];
}
template <typename T>
T& MyArray<T>::operator[](int index) {
if (index>size || index<0){
cout<<"Illegal index"<<endl;
exit (1);
}
assert(index >=0 && index < size);
return data[index];
}
template <typename T>
int MyArray<T>::getSize() const {
return size;
}
template <typename T>
int MyArray<T>::getCapacity() const {
return capacity;
}
template <typename T>
void MyArray<T>::grow(){
T *new_a = new T[(capacity*2)+1];
for (int i = 0; i < size; i++){
*(new_a+i) = *(data+i);
}
//capacity = (capacity*2)+1;
delete [] data;
data = new_a;
}
template <typename T>
int MyArray<T>::getIndex(T a){
for(int i = 0; i < size; i++){
if(*data[i] == *a){
return i;
}
}
return -1;
}
template <typename T>
void MyArray<T>::push_back(T e) {
if(size>=capacity){
grow();
//data[size++] = e;
}
else
assert(size < capacity);
data[size++] = e;
}
template <typename T>
void MyArray<T>::erase(int index){
if(index != -1){
for (int i = index; i <= size; i++){
data[size] = data[i + 1];
}
data[index] = data[index-1];
size--;
}
else cout<<"Cannot find array"<<endl;
}
template <typename T>
void printHeap(MyArray<T> &m) {
for(int i=0; i<m.getSize();i++) {
cout << *(m[i]) << " ";
}
cout << endl;
}
int main() {
cout << endl;
MyArray<int*> Mnums(14);
for(int i=0; i<Mnums.getCapacity(); i++) {
int *nums = new int(i+1);
Mnums.push_back(nums);
}
printHeap(Mnums);
//int *num=new int(4);
int *num1 = new int (3);
//int num1 = 3;
int num2 = 3;
//gets index of the value in that location of the array
cout<<*num1<<" is at index "<<Mnums.getIndex(num1);
cout<<endl;
//adds a value to the array
Mnums.push_back(num1);
printHeap(Mnums);
//displays the size of the array
cout<<Mnums.getSize();
cout<<endl;
Mnums.erase(num2);
printHeap(Mnums);
cout<<Mnums.getSize();
cout << endl;
return 0;
}
Trending now
This is a popular solution!
Step by step
Solved in 3 steps with 1 images