Arrays are great for learning the concepts of coding and as such I endorse them much more than any other standard template library (when it comes to learning code).
Note:
It is wise to use a vector
however the reason schools don’t teach this is because they want you to understand the underlying concepts behind things such as a vector
, stack
, or queue
. You can’t create a car without understanding the parts of it.
Sadly when it comes to resizing arrays there is no easy way other than to create a new array and transfer the elements. The best way to do this is to keep the array dynamic.
Note my example is for int
(s) so you will have to make it into a template or change it to your desired class.
#include <iostream>
#include <stdio.h>
using namespace std;
static const int INCREASE_BY = 10;
void resize(int * pArray, int & size);
int main() {
// your code goes here
int * pArray = new int[10];
pArray[1] = 1;
pArray[2] = 2;
int size = 10;
resize(pArray, size);
pArray[10] = 23;
pArray[11] = 101;
for (int i = 0; i < size; i++)
cout << pArray[i] << endl;
return 0;
}
void resize(int * pArray, int & size)
{
size += INCREASE_BY;
int * temp = (int *) realloc(pArray, size);
delete [] pArray;
pArray = temp;
}
solved How do I Increase the size of a Class array? in turbo c++