What is the difference between std::array and std::vector? When do you use one over other?
I have always used and considered std:vector as an C++ way of using C arrays, so what is the difference?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
std::arrayis just a class version of the classic C array. That means its size is fixed at compile time and it will be allocated as a single chunk (e.g. taking space on the stack). The advantage it has is slightly better performance because there is no indirection between the object and the arrayed data.std::vectoris a small class containing pointers into the heap. (So when you allocate astd::vector, it always callsnew.) They are slightly slower to access because those pointers have to be chased to get to the arrayed data… But in exchange for that, they can be resized and they only take a trivial amount of stack space no matter how large they are.[edit]
As for when to use one over the other, honestly
std::vectoris almost always what you want. Creating large objects on the stack is generally frowned upon, and the extra level of indirection is usually irrelevant. (For example, if you iterate through all of the elements, the extra memory access only happens once at the start of the loop.)The vector’s elements are guaranteed to be contiguous, so you can pass
&vec[0]to any function expecting a pointer to an array; e.g., C library routines. (As an aside,std::vector<char> buf(8192);is a great way to allocate a local buffer for calls toread/writeor similar without directly invokingnew.)That said, the lack of that extra level of indirection, plus the compile-time constant size, can make
std::arraysignificantly faster for a very small array that gets created/destroyed/accessed a lot.So my advice would be: Use
std::vectorunless (a) your profiler tells you that you have a problem and (b) the array is tiny.