Hi, I'm doing some assignment and got stuck at one point here. I am trying to write an list_add() function. The first functionality of it is to add values to the array. The second functionality for it is to increase the size of the array. So it works much like a vector. I dunno if I get it right though. What I tried is to create a new dynamic allocated array which is larger than the old one, and then copy over all the values to the new array.
Is it the right approach?
Here's the main body
int main()
{
const int N = 7;
//declaring dynamic array allocation
int* list = new int[N];
int used = 0, a_val;
for(int i=0;i<11;i++)
{
list_add(list, used, N, i);
}
cout << endl << "Storlek: " << N << endl << endl;
cout << "Printar listan " << endl;
for(int i=0;i<used;i++)
{
cout << list[i] << ". ";
}
}
Here's the function
bool list_add(int *list, int& space_used, int max_size, int value)
{
if(max_size-space_used > 0)
{
*(list+(max_size-space_used-1)) = value;
space_used++;
return true;
}
else
{
cout << "Increasing size of array!" << endl;
int new_max_size = space_used+1;
delete [] list;
int *list_new = new int[new_max_size];
for(int i=0; i<new_max_size; i++)
{
list_new[i] = i;
cout << list_new[i] << ". ";
}
cout << endl;
space_used++;
list = list_new;
return false;
}
}