Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing incremental array in C++

I want to implement an array that can increment as new values are added. Just like in Java. I don't have any idea of how to do this. Can anyone give me a way ?

This is done for learning purposes, thus I cannot use std::vector.

like image 831
Jayanga Kaushalya Avatar asked Nov 28 '25 17:11

Jayanga Kaushalya


1 Answers

Here's a starting point: you only need three variables, nelems, capacity and a pointer to the actual array. So, your class would start off as

class dyn_array
{
    T *data;
    size_t nelems, capacity;
};

where T is the type of data you want to store; for extra credit, make this a template class. Now implement the algorithms discussed in your textbook or on the Wikipedia page on dynamic arrays.

Note that the new/delete allocation mechanism does not support growing an array like C's realloc does, so you'll actually be moving data's contents around when growing the capacity.

like image 51
Fred Foo Avatar answered Nov 30 '25 07:11

Fred Foo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!