C++ I am making a vector and I can\'t seem to figure out the last two steps. I n
ID: 3862220 • Letter: C
Question
C++
I am making a vector and I can't seem to figure out the last two steps. I need to ...
a. A function pop_back( ) that removes the last used element in the vector.
b. A function at(int n) that returns the value of the element at position n in the vector. If the index n is greater than the size( ) of the vector, this function should throw an exception.
below is in my DynArray.cpp file
void DynArray::pop_back(int)
{
delete data[arraySize + 1]; //doesn't work..
//needs to delete the last thing pushed back.
}
int DynArray::at(int) const
{
.
return 0;
}
Explanation / Answer
#include <iostream>
//a. A function pop_back( ) that removes the last used element in the vector.
void DynArray::pop_back()
{
//delete data[arraySize + 1]; //doesn't work..
//needs to delete the last thing pushed back.
int *newData = new int[size()-1]; //Creates a new dynamic array of size 1 less than the current size.
for(int i = 0; i < size()-1; i++) //Copies all the elements from the old array, to new array except the last one.
*(newData+i) = data[i];
delete data; //Frees the previous memory.
data = newData; //Now data points to the newly allocated memory, which is of size one less than the previous one.
size--; //Reduces the size by 1.
}
//b. A function at(int n) that returns the value of the element at position n in the vector.
//If the index n is greater than the size( ) of the vector, this function should throw an exception.
int DynArray::at(int index) const
{
if(index < size() && index >= 0)
return data[index];
return 0;
}
If this doesn't work, just post the whole DynArray class and if possible also the demo class.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.