I'm trying to delete "GoodBye" from the Remove
function and then print a list with it missing.
I'm getting an error saying:
Error 1 error C2440: 'delete' : cannot convert from 'std::string' to 'void*
#include <iostream>
#include <string>
using namespace std;
const int SIZE = 5;
template <class New_Type>
class Array_Class
{
public:
Array_Class();
~Array_Class();
void Add(New_Type item);
int Search(New_Type item);
void Remove(New_Type item);
void Print();
private:
New_Type *A;
New_Type word;
int count;
};
template <class New_Type>
Array_Class<New_Type>::Array_Class()
{
cout << "You are inside the default constructor.\n";
cout << "New_Type has a size of " << sizeof(New_Type) << " bytes\n\n";
count = 0;
A = new New_Type[SIZE];
}
template <class New_Type>
Array_Class<New_Type>::~Array_Class()
{
cout << "The Destructor has been called.\n\n";
delete[] A;
count = 0;
A = 0;
}
template <class New_Type>
void Array_Class<New_Type>::Add(New_Type item)
{
if (count<SIZE)
{
A[count++] = item;
}
else
{
cout << "The array is full.\n";
}
}
template <class New_Type>
int Array_Class<New_Type>::Search(New_Type item)
{
int i;
for (i = 0; i<count; i++)
{
if (item == A[i])
{
return i;
}
}
return -1;
}
item
is Goodbye. word
will save the copy that gets deleted.
template <class New_Type>
void Array_Class<New_Type>::Remove(New_Type item)
{
int i;
word = item;
for (i = 0; i < count; i++)
{
if (item == A[i])
{
delete A[i];
}
}
}
template <class New_Type>
void Array_Class<New_Type>::Print()
{
int i;
for (i = 0; i<count; i++)
{
cout << "A[" << i << "] = " << A[i] << endl;
}
}
The main function which will add "GoodBye" and other words to my_String
.
int main()
{
Array_Class<string> my_String;
Array_Class<int> my_Ints;
Array_Class<char> my_Chars;
my_String.Add("Hello");
my_String.Add("GoodBye");
my_String.Add("ComeHere");
my_String.Add("SayNo");
my_Chars.Add('a');
my_Chars.Add('b');
my_Chars.Add('c');
my_Chars.Add('d');
my_Chars.Add('e');
my_Chars.Add('f');
my_Chars.Add('g');
my_String.Print();
my_Ints.Print();
my_Chars.Print();
cout << endl;
my_String.Search("Hello");
my_String.Search("SayNo");
my_String.Remove
will remove GoodBye
from my_String
:
my_String.Remove("GoodBye");
my_String.Print();
return 0;
}
The problem is that your Remove
function should not be issuing any calls to delete
. What it should be doing is shifting the elements "up" by one and decreasing the count
member variable. This in effect "removes" the item from the Array.
To shift the elements up, you write a loop where you replace element i
with element i+1
, where you start the loop at the item you want to remove.