Add/Remove element in array

Jul 26, 2014 at 2:34am
I want to learn how to add or remove elements in arrays. Anyone know?
Jul 26, 2014 at 2:48am
A static array can't exactly add/remove elements to it. You can move around elements though to make it appear like this. A dynamic array you can add/remove though could be a tedious task. It is probably best for you to use a dynamic container such as std::vector
Jul 26, 2014 at 2:53am
That depends on what you are trying to do. There are a lot of array-like structures that might be easier to manage than a basic array. Effectively you cannot add or remove items from an array. You can assign values to positions in an array, but the memory is always allocated when the array is created. int A[10]; will allocate a contiguous chunk of memory to store 10 integer values. To "add" a value to the array, you simply set the value at a specific position. A[0] = 12; You need to keep track of how many elements you have stored in the array manually with another variable.

1
2
3
4
5
6
7
8
9
10
int size = 0;
int A[10];

int addToArray(int value) {
  if(size < 10) {
    A[size] = value;
    size++;
  }
  return size;
}


There is also a structure called a vector that abstract all of that work for you, but if you are just learning arrays, you may want to wait on that.

1
2
vector<int> A(10);
A.push_back(12);
Last edited on Jul 26, 2014 at 2:54am
Jul 26, 2014 at 2:53am
Typically, an array contains space for N elements, but only k elements are in use (k < N).

Since C++ arrays start at 0, that means k, if less than N, is the index of the first unused element.

So to add an element, assign value to the element at k, then increment k.
Likewise, to remove an element at i, decrement k then copy/move/swap the value at k to i.

If you wish to maintain some sorted order, you must first find the final location for the element (the place to insert). Again we'll call it i. Increment k, shift the elements from i..k-1 to i+1..k, and assign the new value to element i.

Likewise, to delete element i, shift elements i+1..k to i..k-1 and decrement k.

Hope this helps.
Jul 26, 2014 at 9:44pm
thank you so much!
Aug 15, 2014 at 3:42am
Your welcome!
Aug 15, 2014 at 5:56am
Please don't bump old threads for spam.
Topic archived. No new replies allowed.