Discussion
Team LiB
Previous Section Next Section

Discussion

You can insert elements into sequences at different points using insert, and you can append elements to sequences in various ways including:



vector<int> vec;                      // vec is empty


vec.resize(vec.size() + 1, 1);        // vec contains { 1 }


vec.insert(vec.end(), 2);             // vec contains { 1, 2 }


vec.push_back(3);                     // vec contains { 1, 2, 3 }



Of all forms, push_back alone takes amortized constant time. The other forms' performance can be as bad as quadratic. Needless to say, beyond small data volumes that makes those alternatives potential scalability barriers. (See Item 7)

push_back's magic is simple: It expands capacity exponentially, not by a fixed increment. Hence the number of reallocations and copies decreases rapidly with size. For a container populated using only push_back calls, on average each element has been copied only onceregardless of the final size of the container.

Of course, resize and insert could employ the same strategy, but that is dependent on the implementation; only push_back offers the guarantee.

Algorithms can't call push_back directly because they don't have access to the container. You can ask algorithms to use push_back anyway by using a back_inserter.

    Team LiB
    Previous Section Next Section