I have been assigned a lab where I will be shrinking and growing an array using pointers and it must be done in a function called
void manageArray( istream& in, ostream& out )
The initial size of the array will be 10.
When the array is full, double the size of the array.
When the array is half full after a removal,reduce the size of the array by half.
I have no idea what any of this means, I haven't learned what a dynamic array is and do not know where to start. Any help is appreciated
Do you have to do it with istream and ostream? Or does it just have to be a function? If it only needs to be a function there is an almost identical program in a book called "Jumping into C++" Here's how it goes there:
1 2 3 4 5 6 7 8 9 10 11
int *manageArray(int *p_values,int curr_size) /*curr_size is the size of the
pointer,and p_values are the values of the past values*/
{
int *p_new_values = newint[ cur_size * 2 ];
for ( int i = 0; i < cur_size; ++i )
{
p_new_values[ i ] = p_values[ i ];
}
delete p_values;
return p_new_values;
}
And you use it in main like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
int next_element = 0;
int size = 10;
int *p_values = newint[ size ];
int val;
cout << "Please enter a number: ";
cin >> val;
while ( val > 0 )
{
if ( size == next_element + 1 )
{
// now all we need to do is implement growArray
p_values = growArray( p_values, size );
}
p_values[ next_element ] = val;
cout << "Please enter a number (or 0 to exit): ";
cin >> val;
}
If you know pointers, this should be pretty clear to you ^_^ if not, read a few more tutorials.