C++ Primer 4/e 在vector這裡有一個關鍵概念:『A central property of vectors (and the other library containers) is that they are required to be implemented so that it is efficient to add elements to them at run time. Because vectors grow efficiently, it is usually best to let the vector grow by adding elements to it dynamically as the element values are known.
As we’ll see in Chapter 4, this behavior is distinctly different from that of built-in arrays in C and for that matter in most other languages. In particular, readers accustomed to using C or Java might expect that because vector elements are stored contiguously, it would be best to preallocate the vector at its expected size. In fact, the contrary is the case, for reasons we’ll explore in Chapter 9.』
以及一個當心的提示:『Although we can preallocate a given number of elements in a vector, it is usually more efficient to define an empty vector and add elements to it (as we’ll learn how to do shortly).』
中文版的是這樣說:『vectors(及其他程式庫容器)的一個重要特性是,它們必須能夠在執行期高效地被添加元素。由於vectors能夠高效成長,所以通常最好在元素值已知時才加入元素,讓vector自己動態成長。
一如我們將在第4章所見,這個行為和C內建的arrays以及大部分其他語言的類似東西十分不同。尤其是習慣使用C或Java的讀者,或許會認為vector的元素是連續存放,因此先把vector配置為某預期大小是最好的方法。事實上相反,第9章會探討理由。』
這個當心是這樣寫的:『雖然我們可以為vector預先配置已知個數的元素,但通常定義一個空的vector然後加入元素較有效率。我們很快就會學到如何這麼做。
以前寫C的時候對於未知個數的array就無輒,要改用malloc去配置記憶體,還覺得滿麻煩的,後來用PHP就沒有這些限制,所以C++有這個vector template的概念真是太帥了,我喜歡。