1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
|
#include <cstdlib>
#include <string>
#include <iostream>
string* addEntry(string *dynamicArray[], int &stringSize, string newEntry); //adds entry to dynamic array
string *deleteEntry(string *dynamicArray[], int &stringSize, string entryToDelete); //removes entry to dynamic array
void printString(string &dynamicArray[], int stringSize); //prints out array
using namespace std;
int main()
{
int stringSize = 5; //size of string array
string *names=new string[stringSize]; //dynamic array, size dependant upon runtime
names[0] = "Alex";
names[1] = "Cozi";
names[2] = "Kevin";
names[3] = "Tom";
names[4] = "Stelios";
cout << "Here is the starting list: ";
printString(names, stringSize); //function call to print names
names = addEntry(names, stringSize, "Alex");
names = addEntry(names, stringSize, "Cozi");
names = addEntry(names, stringSize, "Kevin");
names = addEntry(names, stringSize, "Tom");
names = addEntry(names, stringSize, "Stelios");
cout <<"Here are the entered names: " <<endl;
printString(names, stringSize);
names=deleteEntry(names, stringSize, "Stelios");
names=deleteEntry(names, stringSize, "Cozi");
cout <<"After deleting names, here are the remaining entries: " <<endl;
printString(names, stringSize);
delete[] names;
return 0;
}
string *addEntry(string *dynamicArray[], int &stringSize, string newEntry)
{
string *newNames = new string[stringSize +1];
for (int i = 0; i < stringSize; i++)
{
newNames[i]=dynamicArray[i];
}
newNames[stringSize]= newEntry;
stringSize++;
delete[] dynamicArray; //delete array, reallocate memory
return newNames; //return new array information
}
string *deleteEntry(string *dynamicArray[], int &stringSize, string entryToDelete)
{
string *deleteResult = dynamicArray;
int count;
count = 0; //initialize starting value for count
for (int i = 0; i < stringSize; i++)
{
if(dynamicArray[i] = entryToDelete)
{
count = i;
break;
}
}
if (count == 1) //if entry is not found, return the list
{
return deleteResult;
}
else //return update list
{
deleteResult = new string[stringSize - 1];
int count = 0;
for (int i =0; i <stringSize; i++)
{
if(i!=count)
{
deleteResult[count]=dynamicArray[i];
count++;
}
}
stringSize--;
delete[] dynamicArray;
}
return deleteResult;
}
void printString(string &dynamicArray[], int stringSize)
{
for (int i =0; i < stringSize; i++)
{
cout << *(dynamicArray + i) << endl;
}
}
|