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的概念真是太帅了,我喜欢。