Beside the fact, that push_back(x)
does the same as insert(x, end())
(maybe with slightly better performance), there are several important thing to know about these functions:
push_back
exists only on BackInsertionSequence
containers - so, for example, it doesn't exist on set
. It couldn't because push_back()
grants you that it will always add at the end.FrontInsertionSequence
and they have push_front
. This is satisfied by deque
, but not by vector
.insert(x, ITERATOR)
is from InsertionSequence
, which is common for set
and vector
. This way you can use either set
or vector
as a target for multiple insertions. However, set
has additionally insert(x)
, which does practically the same thing (this first insert in set
means only to speed up searching for appropriate place by starting from a different iterator - a feature not used in this case).Note about the last case that if you are going to add elements in the loop, then doing container.push_back(x)
and container.insert(x, container.end())
will do effectively the same thing. However this won't be true if you get this container.end()
first and then use it in the whole loop.
For example, you could risk the following code:
auto pe = v.end();
for (auto& s: a)
v.insert(pe, v);
This will effectively copy whole a
into v
vector, in reverse order, and only if you are lucky enough to not get the vector reallocated for extension (you can prevent this by calling reserve()
first); if you are not so lucky, you'll get so-called UndefinedBehavior(tm). Theoretically this isn't allowed because vector's iterators are considered invalidated every time a new element is added.
If you do it this way:
copy(a.begin(), a.end(), back_inserter(v);
it will copy a
at the end of v
in the original order, and this doesn't carry a risk of iterator invalidation.
[EDIT] I made previously this code look this way, and it was a mistake because inserter
actually maintains the validity and advancement of the iterator:
copy(a.begin(), a.end(), inserter(v, v.end());
So this code will also add all elements in the original order without any risk.