I understand the general differences between insert
and emplace_back
for std::vector
and std::list
. Normally, I would just use emplace_back
any time I want to append an element. For some applications, I need to append the element and have an iterator pointing to that newly appended element.
So typically, I've been doing something like:
// for a vector
std::vector<T> v{store some stuff......};
v.emplace_back(new thing);
auto it = v.end() - 1; // now it points to newly inserted element
// for a list
std::list<T> l{store some stuff......};
l.emplace_back(new thing);
auto it = l.end();
--it; // now it points to newly inserted element
But I'm wondering if it's better to use:
// for a vector
std::vector<T> v{store some stuff......};
auto it = v.insert(v.end(), new thing);
// for a list
std::list<T> l{store some stuff......};
auto it = l.insert(l.end(), new thing);
I imagine the difference is negligible if T
is a POD. But if T
was some non-POD, which one would be faster if I ultimately want to append and acquire the iterator to the newly appended item? From my understanding, you have to balance the pros of using emplace
, which constructs an in-place object without copies unlike insert
, vs. the pros of using insert
, which really is just giving me an iterator directly seemingly no other benefits. To me, it seems it would be faster to use emplace
as the extra step of incrementing an iterator is much less expensive than creating a copy of the object?
I have no clue about any impact on performances (although I cannot imagine any difference) but if you want to append a new element and obtain a reference on it, you can write
auto &r=v.emplace_back(a, b, c);
if you prefer to obtain an iterator on it, you can write
auto it=v.emplace(cend(v), a, b, c);
As far as I can see in the documentation, the only difference is the return type.