Tuesday, June 24, 2008

vectorS Grow Dynamically

C++ Primer 4/e in 3.3. Library vector Type there is a key concept:『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.』
and a beware :『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).』
Chinese translation is said:『vectors(及其他程式庫容器)的一個重要特性是,它們必須能夠在執行期高效地被添加元素。由於vectors能夠高效成長,所以通常最好在元素值已知時才加入元素,讓vector自己動態成長。
一如我們將在第4章所見,這個行為和C內建的arrays以及大部分其他語言的類似東西十分不同。尤其是習慣使用C或Java的讀者,或許會認為vector的元素是連續存放,因此先把vector配置為某預期大小是最好的方法。事實上相反,第9章會探討理由。』
這個當心是這樣寫的:『雖然我們可以為vector預先配置已知個數的元素,但通常定義一個空的vector然後加入元素較有效率。我們很快就會學到如何這麼做。
Before wrote C codes I was unable to solve unknown size array.I need to change using malloc() to allocate memory.Also I thinks it is veryl trouble.And later I use PHP and there is no limits the size.So C++ has the concept of the vector template.It's very coll.I like it.

achi's Blog

No comments: