Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use std::vector instead of array [duplicate]

The way I see this, they both have the same function except std::vector seems more flexible, so when would I need to use array, and could I use std::vector only? This is not a new question, the original questions didn't have the answers I was looking for

like image 686
Lendrit Ibrahimi Avatar asked Jun 10 '26 20:06

Lendrit Ibrahimi


2 Answers

One interesting thing to note is that while iterators will be invalidated in many functions with vectors, that is not the case with arrays. Note: std::swap with std::array the iterator will still point to the same spot.

See more: http://en.cppreference.com/w/cpp/container/array

Good summary of advantages of arrays: https://stackoverflow.com/a/4004027/7537900

This point seemed most interesting:

fixed-size arrays can be embedded directly into a struct or object, which can improve memory locality and reducing the number of heap allocations needed

Not having tested that, I'm not sure it's actually true though.

Here is a discussion in regards to 2D Vectors vs Arrays in regards to the competitive programming in Code Chef: https://discuss.codechef.com/questions/49278/whether-to-use-arrays-or-vectors-in-c

Apparently memory is not contiguous in 2 dimensions in 2D vectors, only one dimension, however in 2D arrays it is.

like image 162
autisticvegan Avatar answered Jun 13 '26 13:06

autisticvegan


As a rule of thumb, you should use:

  • a std::array if the size in fixed at compile time
  • a std::vector is the size is not fixed at compile time
  • a pointer on the address of their first element is you need low level access
  • a raw array if you are implementing a (non standard) container

Standard containers have the ability to know their size even when you pass them to other function, what raw arrays don't, and have enough goodies to never use raw arrays in C++ code without specific reasons. One could be a bottleneck that would require low level optimization, but only after profiling to identify the bottleneck. And you should benchmark in real condition whether the standard containers actually add any overload.

The only good reason I can think of is if you implement a special container. As standard containers are not meant to be derived, you have only two choices, either have you class contain a standard container and end in a container containing a container with delegations everywhere, or mimic a standard container (by copying code from a well knows implementation), and specialize it. In that case, you will find yourself managing directly raw arrays.

like image 27
Serge Ballesta Avatar answered Jun 13 '26 13:06

Serge Ballesta