I have tried several different things and researched this for hours. Most of the responses say to just use the vector class but this is for homework which helps us understand memory allocation and dynamic arrays. Currently this is my .cpp and .h file that is giving me problems. Every time the delete (or the clear function) operation is triggered an error occurs that states blahblah.exe has triggered a break point.
MyVector.h
#pragma once
class MyVector
{
private:
int arraySize;
int arrayCapacity;
int* theData;
void grow();
public:
MyVector();
MyVector(int n);
int size() const;
int capacity() const;
void clear();
void push_back(int n);
int& at(int n);
~MyVector();
};
MyVector.cpp
#include "MyVector.h"
#include <iostream>
using namespace std;
MyVector::MyVector()
{
arraySize = 0;
arrayCapacity = 0;
theData = new int[0];
}
MyVector::MyVector(int capacityIn)
{
int* theData = new int [capacityIn];
}
int MyVector::size() const
{
return arraySize;
}
int MyVector::capacity() const
{
return arrayCapacity;
}
void MyVector::clear()
{
delete [] theData;
theData = nullptr;
}
void MyVector::push_back(int n)
{
if (arrayCapacity==0)
{
arrayCapacity++;
MyVector(arrayCapacity);
}
if (arraySize == arrayCapacity)
{
grow();
MyVector(arrayCapacity);
}
theData[arraySize] = n;
arraySize++;
}
int& MyVector::at(int index)
{
if (index >= 0 && index<arraySize)
{
return (theData[index]);
}
else
{
throw index;
}
}
void MyVector::grow()
{
arrayCapacity = arrayCapacity + arrayCapacity;
}
MyVector::~MyVector()
{
if (theData != nullptr)
{
clear();
}
}
Aucun commentaire:
Enregistrer un commentaire