Vector vs Array | Sololearn: Learn to code for FREE!

+3

Vector vs Array

Working of both vector and array are mostly similar.. The major difference between vector and array is that we dont have to specify size in vector while in array we have to.. So my question is which of the following should be used and Why?? Which of the following have more advantages??

8/6/2019 6:16:02 PM

Alaska

4 Answers

New Answer

+3

std::array allocates on the stack and std::vector allocates its array on the heap so creating and accessing an std::array is faster because it avoids a new call. std::vector also has 2 more variables that keep track of it's size and capacity so it is also bigger than an std::array, but only slightly. But this is neglectable. Creating a big array on the stack usually isn't the best idea either so unless your array is small that gets created or accessed alot you're usually better off with a std::vector.

+2

You already answered your own question. If you know the size at compile time use an std::array. Otherwise default to an std::vector.

+2

The „C++ Core Guidelines“ recommend: „Usually you need to add and remove elements from the container, so use vector by default; if you don’t need to modify the container’s size, use array. Even when other containers seem more suited, such a map for O(log N) lookup performance or a list for efficient insertion in the middle, a vector will usually still perform better for containers up to a few KB in size.“ reference: http://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines

0

Dennis 😅😅 I know..But my question was what are other differences and which is recommended to use..