Hello, what are the differences between vectors and arrays? When to use one or another? Thanks!!
A vector is a proper C++ container object. It will resize as needed, and responds to various function calls; you can ask it how many objects it's holding, you can ask it to resize, you can ask it to reserve some memory for future resizing, you can add objects to it and it will automatically resize itself, and various other very useful functions. It takes care of its own memory so you don't have to worry about it.

An array is naked memory. You get some memory, you put some objects next to each other in it. It's up to you to know how big it is, how many objects you've actually put in it, if you need to resize it, doing the actual resizing, everything. It's dangerous and a common source of mistakes.

Use vector always. Use array never.

The corollary to that is in special cases, when you simply have to use an array, redesign your code so you can use a vector instead.

If you're using legacy code of some kind that demands an array, still don't. Use a vector, and feed whatever wants the array a pointer to the first element in the vector. It will look the same to whatever it is that wants the array, and limit the danger to that old bad code rather than letting it infect your new code.

What I'm really saying here is that you really, really should try very hard to never use an array. If some situation comes up in which you have no choice, and you can't redesign the code, well, that's how it is, but that's a bad situation to be in.

A lot of beginners learn arrays first. This is just plain crazy and I suspect a leftover from teachers who grew up with C and think of C++ as basically C with some extra bits. Arrays are not for beginners because they don't work how beginners expect them to and they get in the way of programming and thinking and learning how to program. In C++, the basic container is a vector. Arrays are for later once you understand memory and are fluent with pointers and can reason about memory safety, and even then, don't use them. Use a vector.
Last edited on
Topic archived. No new replies allowed.