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

2020-02-03 16:15发布

问题:

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?

回答1:

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.



回答2:

I only really use arrays when working with embedded systems, or when certain APIs require it (ie take them in as an argument for a function). Also, if there are only one or two places where I'd need to use arrays, or don't specifically need vector functionality, it makes more sense to use arrays just because of the additional overhead of vector.h.

Otherwise, just use vectors :)