Home > Enterprise >  When do we use arrays over vectors in C and vice versa?
When do we use arrays over vectors in C and vice versa?

Time:10-25

I saw the following from this link:

Vectors are part of STL. Vectors in C are sequence containers representing arrays that can change their size during runtime . They use contiguous storage locations for their elements just as efficiently as in arrays, which means that their elements can also be accessed using offsets on regular pointers to its elements.

Vectors are the dynamic arrays that are used to store data.It is different from arrays which store sequential data and are static in nature, Vectors provide more flexibility to the program. Vectors can adjust their size automatically when an element is inserted or deleted from it.

If vectors can do so much, under what circumstances do we still prefer arrays?

Thanks!

CodePudding user response:

If vectors can do so much, under what circumstances do we still prefer arrays?

A good design is not when there is nothing left to add, rather when there is nothing left to remove. Or introducing extra complexity only when it is needed.

CodePudding user response:

One major disadvantage of std::vector is that it uses dynamic memory allocation whenever it must grow, which can be quite expensive in terms of execution time. Therefore, in situations when a reasonable upper limit is known, it may be better to use a fixed-length array, even if this wastes memory space. This decision is a space/time trade-off.

However, this disadvantage of std::vector can be mitigated by reserving memory for a certain amount of elements in advance, by calling std::vector::reserve.

Another disadvantage of using std::vector is that serialization is significantly harder. For example, if you make a std::array a member of a struct, then you can simply copy the entire struct contents byte by byte in order to serialize it. However, this is not possible if you make a std::vector a member of a struct, as it will probably not store the actual data inside the struct, but will probably only store a pointer to the data. Therefore, you will be unable to serialize the struct by simply copying the memory of the struct. Instead, serializing the std::vector will require special treatment.

  • Related