Hey Im working on this program for school, pretty much I have to create an array of five strings and create and use two functions, addEntry and deleteEntry. These should allow you to change the size and add elements to the array or emulate the functions of a vector as the book says. So far I have the addEntry working but when I tried to put in my deleteEntry I now get an error saying the .exe has stopped working. Can you help me out? I muct have made the deleteEntry Function wrong or something.
Here's my code:
Code:
//COT 3002
//The purpose of this program is to create a function that can add or remove elements to an array
#include <iostream>
#include <cstring>
#include <string>
using namespace std;
//Function Prototypes
string* addEntry(string *dynamicArray, int &size, string newEntry);
string* deleteEntry(string *dynamicArray, int &size, string entryToDelete);
int main()
{
int size=5;
string *strPtr=new string[size];
int i=0;
strPtr[i++] = "Frink";
strPtr[i++] = "Wiggum";
strPtr[i++] = "Nahasapeemapetilon";
strPtr[i++] = "Quimby";
strPtr[i++] = "Flanders";
cout<<"Initial List:"<<endl;
for(i=0; i < size; i++)
cout << i << ": " << strPtr[i] << endl;
cout<<"\nAfter Adding an Entry:"<<endl;
strPtr=addEntry(strPtr, size,"Spuckler");
for(i=0; i < size; i++)
cout << i << ": " << strPtr[i] << endl;
strPtr=deleteEntry(strPtr, size, "Nahasapeemapetilon");
for(i=0; i < size; i++)
cout << i << ": " << strPtr[i] << endl;
return 0;
}
string *deleteEntry(string *dynamicArray, int &size, string entryToDelete)
{// create a new dynamic array 1 element larger than dynamicArray
string *newArray = new string[size - 1];
// copy all elements from dynamicArray into new array
for(int i = 0; i < size; i++)
{
if(dynamicArray[i]!=entryToDelete)
newArray[i] = dynamicArray[i];
}
size--;
// delete dynamicArray
delete [] dynamicArray;
// and return the new array
return newArray;
}
string *addEntry(string *dynamicArray, int &size, string newEntry)
{
// create a new dynamic array 1 element larger than dynamicArray
string *newArray = new string[size + 1];
// copy all elements from dynamicArray into new array
for(int i = 0; i < size; i++)
{
newArray[i] = dynamicArray[i];
}
// add the new entry onto the end of the new array
newArray[size] = newEntry;
// increment size
size++;
// delete dynamicArray
delete [] dynamicArray;
// and return the new array
return newArray;
}