More Thoughts About Arrays and Vectors
My recent comments about teaching vectors instead of arrays to C++ beginners has left an important idea unstated that I think it is worth mentioning explicitly.
One of the most fundamental differences between C and C++ is that C++ has constructors and destructors. This difference gives C++ a philosophical distinction that C lacks between an object and the memory that the object occupies. In C, when you write
you are defining n as a variable of type int with an undefined value. C++ behaves the same way, because int is a built-in type. However, in C++, when you write
you are not only defining s as a variable of type string, but you are also executing code — the string constructor — that causes the object denoted by s to come into existence.
Now consider an array definition:
If the type of ss were int, we would just be allocating memory. However, because ss is a string, we are asking the compiler to construct 30 objects for us. Because C++ (potentially) executes code whenever an object is constructed or destroyed, our definition has turned into a request for action that we do not really need. The distinction between allocation and construction turns an innocent coding technique in C into a bad habit in C++.
To avoid this bad habit, it is necessary to think about containers as data structures with a number of elements that the programmer can change easily and efficiently. Built-in arrays do not allow the number of elements to be changed at all; "dynamic arrays" allocated with new and delete (or with malloc and free) allow the number of elements to be changed only at significant expense. Compared with either of these strategies, using vector, list, or deque executes faster and is also more convenient. In other words, the library containers are usually more efficient than built-in arrays, both in their use of computer time and their use of programmer time.
If you've been reading my articles for long, you know that I consider human time to be worth more than computer time. However, "less important" does not mean "unimportant"; we should always be alert to opportunities to make programming more efficient for both humans and machines.