Dynamically updating arrays

So I know vectors are out there to solve this exact problem, but as a challenge would like to figure out how to dynamically update the size of an array as values are added to it or taken away. Here is some code that I am trying to add this sort of functionality to. And I'm trying to add it to each function. Any help is appreciated.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
  void insert (string ar[], int sz, strinng el, int pos)
{
  for (int i=sz-1; i >=pos; --i)
  {
    are[i+1] = ar[i];
  }
  ar[pos] = el;
  return;
}

string del (string ar[], int sz, int pos)
{
  string result = ar[pos];
  for (int i = pos; i < sz - 1, ++i)
  {
    ar[i]=ar[i+1];
  }
  return result;
}

void append(string ar[], int sz, string el)
{
  ar [sz] = el;
  return;
}
you can't resize arrays. you can resize pointers:

int * a = new int[100];
…//code assigns and does stuff to a.
//oops, made a too small, increase it:
int *tmp = a;
a = new int[1000];
memcpy(a,tmp, sizeof(int)*100);
delete tmp;
tmp = null;

a is resized.

vectors do pretty much the above. It has several optimizations, but resizing these kinds of things is expensive (slow). it is best avoided if at all possible (sometimes, it isn't possible).

if sz is size used and not actual size, you should be good from there.
if you want the actual size to update every time you do an operation, youll need to resize every time, and it will be horribly slow.
Last edited on
Topic archived. No new replies allowed.