I am usually unsure when it is better to use one versus the other. They both seem to do the same things in general but is vector more flexible in terms of what it can do? When are arrays more appropriate?
Array is memory efficient data structure. Vector takes more time in accessing elements. Array access elements in constant time irrespective of their location as elements are arranged in a contiguous memory allocation.
A vector is a dynamic array, whose size can be increased, whereas THE array size can not be changed. Reserve space can be given for vector, whereas for arrays you cannot give reserved space. A vector is a class whereas an array is a datatype.
Vectors C++ are preferable when managing ever-changing data elements. It is handy if you don't know how big the data is beforehand since you don't need to set the maximum size of the container. Since it's possible to resize C++ vectors, it offers better flexibility to handle dynamic elements.
A std::vector can never be faster than an array, as it has (a pointer to the first element of) an array as one of its data members. But the difference in run-time speed is slim and absent in any non-trivial program. One reason for this myth to persist, are examples that compare raw arrays with mis-used std::vectors.
Generally always prefer using std::vector<T>
since the destruction will be automatic once the vector goes out scope and the allocated memory will be placed neatly on the heap and all the memory will be handled for you. std::vector<T>
gives you everything you get in an array and even a guarantee that the elements will be contiguously stored in memory (except for std::vector<bool>
).
In the case of std::vector<bool>
you have to be careful since code like this will break:
std::vector<bool> vb;
vb.push_back(true);
vb.push_back(false);
vb.push_back(true);
bool *pB = &vb[0];
if( *(pB+1) )
{
// do something
}
Fact is, std::vector<bool>
doesn't store contiguous bool
s. This is an exception in the standard that is fixed in C++11.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With