C++ Primer 4/e在Generic Algorithms這個地方有一個關鍵觀念:『The generic algorithms do not themselves execute container operations. They operate solely in terms of iterators and iterator operations. The fact that the algorithms operate in terms of iterators and not container operations has a perhaps surprising but essential implication: When used on “ordinary” iterators, algorithms never change the size of the underlying container. As we’ll see, algorithms may change the values of the elements stored in the container, and they may move elements around within the container. They do not, however, ever add or remove elements directly.
As we’ll see in Section 11.3.1 (p.406), there is a special class of iterator, the inserters, that do more than traverse the sequence to which they are bound. When we assign to these iterators, they execute insert operations on the underlying container. When an algorithm operates on one of these iterators, the iterator may have the effect of adding elements to the container. The algorithm itself, however, never does so.』
中文版的這樣寫:『泛型演算法不執行容器操作。他們只根據iterators和其相關操作來運作。這種「以iterators為基礎」而非「以容器操作為基礎」的事實,驚人(但十分貼近本質)地暗示:當使用一般的(ordinary)iterators時,演算法絕不會改變底層容器的大小。我們也將看到,演算法可能改變容器元素的值,可能在容器中移動元素,但都沒有直接添加或移除元素。
我們將在11.3.1節(p.406)看到一種特殊的iterators:inserter,它在它所綁定的序列尚可進行比尋訪更多的操作。一旦用上這種iterators,iterators本身會對容器添加元素,至於演算法本身從來不這麼做。』
ㄝ!中英文的11.3.1都是在406頁啊!突然注意到這個頁數的問題,沒想到侯捷先生的功力竟然可以翻到同一頁上,佩服阿!
不過我還搞不清泛型眼算法跟容器的操作的差異,有待加強了解!