hi guys,
i want to do this task given by ebook :
Modify the SimpleVector class template presented in this chapter to include the
member functions push_back and pop_back. These functions should emulate the
STL vector class member functions of the same name. (See Table 16-5.) The
push_back function should accept an argument and insert its value at the end of the
array. The pop_back function should accept no argument and remove the last element
from the array. Test the class with a driver program.
then i design push_back and pop_back function for the SimpleVector class :
this is the push_back function =
//aptr is the private member variables, and so does arraySize.
template <class Type>
void SimpleVector<Type>::push_back(int x)
{
if(arraySize > 0)
{
Type* temp = new Type[arraySize];
for(int index = 0; index < arraySize; index++)
{
temp[index] = aptr[index];
}
delete [] aptr;
arraySize += 1;
aptr = new Type[arraySize];
for(int index = 0; index < arraySize - 1; index++)
{
aptr[index] = temp[index];
}
delete [] temp;
aptr[arraySize - 1] = x;
}
else
{
arraySize = 1;
aptr = new Type[arraySize];
aptr[0] = x;
}
}
and this is the pop_back function:
//aptr is the private member variables, and so does arraySize.
template <class Type>
void SimpleVector<Type>::pop_back()
{
arraySize -= 1;
Type* temp = new Type[arraySize];
for(int index = 0; index < arraySize; index++)
{
temp[index] = aptr[index];
}
delete [] aptr;
aptr = new Type[arraySize];
for(int index = 0; index < arraySize; index++)
{
aptr[index] = temp[index];
}
}
my questions are:
- is it correct way to perform push_back and pop_back just like in the STL vector(i tried it and it works, but i dont know if the functions will/wont produce errors)? because i think my push_back and pop_back functions looked awkward :S
- why does my main function need to includes "SimpleVector.h" and "SimpleVector.cpp" ? if it only includes "SimpleVector.h", my main function wont recognize the SimpleVector class template, why does it happen?
note : sorry for the bad english