I'm trying to make an arraylist where I not only can I append(add) and insert, but also make a moving Average function in my arraylist class.
I've tried various research and examples online and I've officially hit a wall. I've also been having a problem with "capacity" where I get a scientific output or a 0 rather than an integer regarding the capacity in my resize() function. Can someone please help me fix my problem. I really need to get this fixed as soon as possible.
#ifndef ARRAYLIST_H_
#define ARRAYLIST_H_
#include<iostream>
using namespace std;
class arrayList{
int size;
int capacity;
double *p;
void resize(){
capacity *= 2; //THIS IS WHAT'S CRASHING THE CODE
double *temp = new double[capacity];
for(int i = 0; i < size; i++){
temp[i] = p[i];
delete []p;
p = temp;
temp = nullptr;
}
}
public:
arrayList(): size(0), capacity(1){
p = new double[capacity];
}
arrayList(int cap): size(0), capacity(cap){
p = new double[capacity];
}
//copy constructor
arrayList(const arrayList& copy){
size = copy.size;
capacity = copy.capacity;
p = new double[capacity];
for(int i = 0; i < size; ++i)
p[i] = copy.p[i];
}
//move constructor
arrayList(arrayList&& move){
size = move.size;
capacity = move.capacity;
p = move.p;
move.size = 0;
move.capacity = 0;
move.p = nullptr;
}
//copy assignment operator
arrayList& operator=(const arrayList& copyA){
if (this != ©A){
size = copyA.size;
capacity = copyA.capacity;
p = new double[capacity];
for(int i = 0; i < copyA.size; ++i)
p[i] = copyA.p[i];
delete []p;
} return *this;
}
// move assignment operator
arrayList& operator=(arrayList moveA){
if (this != &moveA){
size = moveA.size;
capacity = moveA.capacity;
delete []p;
p = moveA.p;
moveA.p = nullptr;
} return *this;
}
//destructor
~arrayList(){
delete []p;
}
void insert (int index, int value){
if (index >= capacity){
cout << "OUT OF BOUNDS!";
}
if(index < size && index >= 0){
for (int i = size; i > index; --i){
p[i] = p[i - 1];
}
p[index] = value;
size++;
} else{
p[index] = value;
size++;
}
}
void append(int val){
if (size == capacity)
resize();
p[size] = val;
size++;
}
void movingAvg(const arrayList& avg, int kernel){
// I REALLY NEED HELP WITH THIS PART.
}
friend ostream& operator<<(ostream& os, arrayList& val){
for(int i = 0; i < val.size; ++i)
os << val.p[i] << " ";
os << endl << endl;
return os;
}
};
// main.cpp
int main(){
arrayList a;
a.append(45);
cout << a;
a.append(14);
cout << a;
a.insert(2, 76);
cout << a;
//CRASHES AT THIS POINT!
a.insert(3, 45);
cout << a;
a.insert(5, 23);
cout << a;
return 0;
}
OUTPUT:
45
45 14
45 14 76 0
Aucun commentaire:
Enregistrer un commentaire