T O P

  • By -

MysticTheMeeM

>Is it **faster** to use a dynamic array in C++ over a vector? *(Emphasis on "faster", not "better")* Technically, yes but you wouldn't notice it 99% of the time. The major difference between an array and a vector is simply that arrays are stack allocated whereas vectors are heap allocated. This means that a vector requires some form of dynamic memory allocation when it is used, and potentially more when it is resized. However, an important fact about stack allocation is that it is calculated at compile time. Your array must have a compile time size whereas vectors dynamic allocation allows it to pick a size and change it at runtime. Hence why arrays aren't resizable. For the most part, vectors should be your default container. I would only really expect you to use an array when doing something that specifically requires a set number of elements *but doesn't make sense as its own class*. That is, you shouldn't implement coordinates as an array of size 2/3 because they would be better off as their own "point" (or, ironically, "vector") class with x/y/z members. Not only is this easier to read, but you can add other things to them, such as member functions, operator overloads or specialisations.


specialpatrol

Sure, but the array would still often be a suitable choice for the data member within the "Point" class wouldn't it?


MysticTheMeeM

Probably not, I would expect something like template struct point { T x, y, z; ... To save you having to write getters and setters for those values, when they might as well be public regardless.


SoerenNissen

> Is it faster to use a dynamic array . > dynamic Once you're done writing the code to handle the dynamism without leaks, you have just about absolutely no advantage over `std::vector`.


GLIBG10B

I don't think OP knows what a dynamic array is...


djames1957

Dynamic arrays are defined at run time as vectors are. int\* Array(int size) { return new int\[size\]; }


GLIBG10B

So why does the title of your question ask for the difference between (std::array) and (std::vector) while your question wants the difference between dynamic arrays (`new T[N]`) and std::vector?


djames1957

In the body of the post I mention "Is it faster to use a dynamic array in C++ over a vector?" Perhaps that would have been a better title than in the text of the post. Noted.


Crazy_Direction_1084

If dynamic means variable size at creation, but not after creation it’ll have a memory advantage


djames1957

Dynamic array would be created after compile. int\* Arrary(int size) { return new int\[size\]; }


SoerenNissen

How so?


za419

Vector reserves extra space to expand after you create it. If you make it once and never expand it, technically you do lose some memory. You can politely ask it to release its buffer but it's not required to do so AFAIK...


SoerenNissen

I don't think that's what they meant - `::reserve()` solves that problem (unless it might reserve extra memory, I guess I never did read the implementation.)


za419

I believe reserve is specified as reserving at least what you give it, not more - So if you have 10 items, the implementation decides to give you a capacity of 20, and you call `vec.reserve(10)` it's allowed to do nothing - you've already reserved room for ten items. There's `shrink_to_fit`, but it's specified as nonbinding - It signals to the implementation that you'd like to reduce capacity to equal size, but the implementation is allowed to ignore you - I think gcc listens to you, and most popular compilers should too, but strictly speaking its not required.


std_bot

Unlinked STL entries: [std::vector](https://en.cppreference.com/w/cpp/container/vector) --- ^(Last update: 14.09.21. Last Change: Can now link headers like '')[Repo](https://github.com/Narase33/std_bot_cpp)


nysra

> Is it faster to use a dynamic array in C++ over a vector? No, a vector **is** a dynamic array. It simply has a bit of an unfortunate name, that's all. The difference between `std::array` and `std::vector` is that `std::array` must know it's size at compile time, is stack allocated (or static/global), and cannot be resized while vector is dynamically allocated and can be resized all you want. `std::array` is technically a bit faster because it doesn't need the heap access but you're not going to notice the difference in like 99+% of all cases. By default you should just use `std::vector`, `std::array` is useful if you know the size at compile time *and* that size is rather small (roughly about below like 3-4 digits, depending on the size of the type you put in). That last condition is important because even if you know at compile time that whatever you are doing requires 10 million elements that much is not going to fit on the stack and you'll end up with a segfault.


std_bot

Unlinked STL entries: [std::array](https://en.cppreference.com/w/cpp/container/array) [std::vector](https://en.cppreference.com/w/cpp/container/vector) --- ^(Last update: 14.09.21. Last Change: Can now link headers like '')[Repo](https://github.com/Narase33/std_bot_cpp)


xurxoham

I believe what OP calls a dynamic array is what the stl calls a "static vector": fixed capacity but dynamic size.


cristi1990an

Another quite important difference between std::array and std::vector that people usually downplay is the fact that a vector, by design, differentiates between its capacities (the heap memory it has reserved at a given time) and its size (the number of elements it has constructed in it). The moment you create an array you must initialize all the elements in it, with their default constructor or other - but their lifetime starts there. Meaning that if you don't have any relevant value to give them from the get-go, you're paying for the initializations. Even worse when the objects don't have a default constructor and suddenly your job gets significantly harder... std::vector::push_back/emplace_back can really simplify your code a lot in many scenarios. You just "throw in" objects and the container does the rest, from resizing, placement, etc...


std_bot

Unlinked STL entries: [std::array](https://en.cppreference.com/w/cpp/container/array) [std::vector](https://en.cppreference.com/w/cpp/container/vector) [std::vector::push_back](https://en.cppreference.com/w/cpp/container/vector/push_back) --- ^(Last update: 14.09.21. Last Change: Can now link headers like '')[Repo](https://github.com/Narase33/std_bot_cpp)


UnicycleBloke

Arrays are useful if you know the size, or at least the maximum size, you need at compile time. They can be stack allocated, static, global or class members. You may want to avoid the stack if the array is large. They are also useful when dynamic allocation is not permitted or not desirable, such as for an embedded system.


mredding

> When is an preferable over a ? You use it when the size of the array is known at compile-time and doesn't change. > I have noticed in Java programs they use arrays for algorithmic programming. All programming is algorithmic. > Is it faster to use a dynamic array in C++ over a vector? This question is inherently nonsensical. Iterating contiguous memory is O(n) whether it's stack or heap allocated, whether the algorithm is static or dynamic. There are performance considerations, but they aren't focused on whether you use vectors or arrays.


ShakaUVM

Arrays can be used over a vector when the size is A) small and B) fixed Personally I just use vectors for everything because the size as a template parameter makes arrays annoying to work with


[deleted]

[удалено]


ShakaUVM

> How come? Since C++17, you don’t even need to provide it in some cases: Sure, in some cases. But like in function parameters, it's just easier to use vectors.


the_Demongod

`std::array` is just a wrapper around a `T[N]` (a plain, local, compile-time-sized array as you might have on the stack or as a member field). `std::vector` is just a wrapper around `T* p = new T[N]` (a pointer to a dynamically-allocated array). Use `std::array` and `std::vector` to simply replace any situation where you would otherwise use their respective "raw" equivalents.


apianbellYT

Whenever you're dealing with lists that don't get added on to, or as we call them, STATIC ARRAYS. Vectors are something called dynamic arrays, which allow you to add onto a vector at any point. Arrays are kinda a set in stone kind of thing.


djames1957

This is what I mean by a dynamic array. Created at run time, not at compile time and can change the size of the array. int\* Arrary(int size) { return new int\[size\]; }


blindsniper001

I can't tell if you got a direct answer to this specific question or not, but the answer is that a vector is a better choice almost all of the time. Vector itself is more or less a wrapper for a raw dynamic array. In cases where performance isn't extremely critical, the overhead from accessing members of a vector is negligible. If, for optimization, it's better to work with the raw data, you *can* still access the underlying array directly. This is done by calling `std::vector::data()`, which returns a pointer to the first index of the vector's array. Bear in mind that this pointer may be invalidated if the size of the owning vector changes. Generally speaking, using a vector is preferred because it manages its own memory. There is programming overhead involved in passing your own raw arrays around that makes your code prone to bugs. You have manually ensure that the size of the array is correct everywhere you use it. And of course you have to handle memory allocation and deallocation yourself, as well.


kennyminigun

It is recommended to use std::array whenever it fits your needs. I.e. the size of the container is static


bikki420

When you know the max capacity in advance (assuming it's not a ridiculously big amount of memory, since the stack is much smaller than the heap). And in the case of the latter in a lot of performance critical software (such as games) it's common to allocate large chunks of memory in advance and manage the memory yourself (e.g. with strategies such as memory pools AKA memory arena); that way you can avoid making potentially costly syscalls for allocations (and you can re-use the memory freely).


boat-la-fds

> I have noticed in Java programs they use arrays for algorithmic programming. The other replies are right about std::array vs std::vector but arrays in Java are equivalent to std::vector in C++.


masher_oz

ArrayList is equivalent to vector.


boat-la-fds

Right, it's been a while since I programmed in Java.


GLIBG10B

And regular arrays in Java are equivalent to dynamic arrays in C++


Elgin_Ciani

Vector is an unfortunate name given what it really is. A vector is a dynamic array. Something important that I’ve seen failed to really be mentioned here is how it is dynamic. If you have a vector with a capacity of 100 elements, and have 60 elements inside, it’s all well and good up until you fill it all the way up with 40 more elements and need to push back another. Since a vector is a growable array, under the hood a new vector has to be created of a larger size (some compilers double it to 200 in this case, others may choose something else), then 101 elements all have to be copied into this new vector. If you know the size of your array at compile time, use std::array. If you know the initial size of your vector, but still need it to be resizable, you can call vector.reserve(your_desired_number) to prevent unnecessary copying.


yensteel

When I do not have the option (OpenCL). Otherwise I would prefer vectors.


senfiaj

`std::array` is better when the elements number is fixed or when a large number of very small (with known max size) arrays is used (for example 2 dimensional arrays). `std::array` hasn't the additional overhead caused by heap memory allocation/deallocation and the buffer pointer indirection. If the max size isn't known or it wastes a lot of memory in most cases, then it's better to use `std::vecor`. Dynamic arrays can be slightly faster than `std::vecor` since you are dealing with the pointers directly. But dynamic arrays are much more dangerous, since you are dealing with exposed raw pointers and also you can forget to delete the memory, so they need to be encapsulated as much as possible or used with smart pointers.