Removing values from Array

A program I am working on requires that I removed zeroed-out values (along with their indices) from an array.

ex. A=[12, 2, 7, 0, 3] ---> A=[12, 2, 7, 3]

I have implemented this in the following way:

* create new array B
* for i=0, i<size(A)
if element != 0, copy it to B
else if element == 0, skip it
* resize A to size of B
* copy all elements from B to A

This seems like a very cumbersome approach to a seemingly simple task. Does anyone know of a more elegant algorithm for doing this?

-Thanks!!
You can do this better using LinkedList Algorithm. LinkedList better suite for your requirement. Google for LinkedList, you will get more tutorials.
Last edited on
Normally, one would use std::vector and std::remove:

http://www.cplusplus.com/reference/stl/vector/
http://www.cplusplus.com/reference/algorithm/remove/

You can also use remove on an array as shown in the example.
Still, since it is not possible resize an array you will have to create a new one with the necessary size and copy the values.
std::vector would make this unnecessary.
Last edited on
Topic archived. No new replies allowed.