Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use vectors instead of arrays?

Tags:

c++

arrays

vector

If I have a fixed number of elements of class MyClass, should I use arrays or vectors?, ie:

MyClass* myArray[];

or

std::vector<MyClass*> myVector;

?

like image 573
Tatanan Avatar asked Dec 11 '25 15:12

Tatanan


2 Answers

Use std::array or raw arrays for a small, static number of elements.

If you have a lot of elements (more than say 100kb), you hog the stack and are asking for stack corruption / overflow. In that case, or if the number of elements can only be known at runtime, use std::vector.

like image 178
tenfour Avatar answered Dec 15 '25 03:12

tenfour


if you know the number in compile time - use static array.

if the number is dynamic (obtained from the user) - vector is much better to save you the hurdle of managing the memory

like image 28
NirMH Avatar answered Dec 15 '25 02:12

NirMH



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!