Examples
Team LiB
Previous Section Next Section

Examples

Example 1: vector::insert. Let's say you want to add n elements into a vector v. Calling v.insert(position,x) repeatedly can cause multiple reallocations as v grows its storage to accommodate each new element. Worse, each single-element insert is a linear operation because it has to shuffle over enough elements to make room, and this makes inserting n elements with repeated calls to the single-element insert actually a quadratic operation! Of course, you could get around the multiple-reallocation problem by calling reserve, but that doesn't reduce the shuffling and the quadratic nature of the operation. It's faster and simpler to just say what you're doing: v.insert(position,first,last), where first and last are iterators delimiting the range of elements to be added into v. (If first and last are input iterators, there's no way to determine the size of the range before actually traversing it, and therefore v might still need to perform multiple reallocations; but the range version is still likely to perform better than inserting elements individually.)

Example 2: Range construction and assignment. Calling a constructor (or assign function) that takes an iterator range typically performs better than calling the default constructor (or clear) followed by individual insertions into the container.

    Team LiB
    Previous Section Next Section