Dynamic Array

How to implement dynamic arrays using normal arrays that work exactly like vectors


One approach is to increase and decrease the space.

Please tell some other good approach?

Also how to reduce the additional overhead of copying the data of array while allocating new space?
That is the only way. You can't reduce the overhead of copying unless you write your own memory manager
that can magically grow the allocated memory block such that it remains contiguous and at the same location.
How are vectors implemented?
Vectors use the same approach???

Yes, they do. Except that they don't shrink when you remove elements.
I hope the question is how do vectors work, rather than how do I implement my own version. The STL is standard, efficient, peer-reviewed, thoroughly tested, maintained elsewhere, and free. It would be a mistake not to take advantage of this and implement a lower quality vector for your own purposes.
If it doesn't need to be compatible with C like apis you can also use std::deque which is a dynamic sequence container. It works like an array and provides similar features as std::vector but it does grow and shrink automatically. It can do this because elements don't have to be contiguous. It is like a linked list of small arrays internally. Therefore it allocates/deallocates small chunks at a time. I agree with everyone else. Learn to use what the STL provides first. If that doesn't work take a look at boost.org and see what they offer. Reinventing the wheel shouldn't really be necessary for the vast majority of software projects.
Topic archived. No new replies allowed.