Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use vectors and when to use arrays in C++?

Tags:

c++

arrays

vector

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?

like image 845
John Smith Avatar asked Jun 02 '12 20:06

John Smith


People also ask

Which is better array or vector?

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.

Which are advantages of a vector over an array?

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.

When should you use vectors?

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.

Are C arrays faster than vectors?

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.


1 Answers

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 bools. This is an exception in the standard that is fixed in C++11.

like image 60
Chris A. Avatar answered Nov 15 '22 22:11

Chris A.