vectorS Grow Dynamically

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).』




以前寫C的時候對於未知個數的array就無輒,要改用malloc去配置記憶體,還覺得滿麻煩的,後來用PHP就沒有這些限制,所以C++有這個vector template的概念真是太帥了,我喜歡。

achi’s English Blog




發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *