When using std::vector
s, std::list
s (or other STL containers), I happen to often write this, for code shortness (rather than putting explicit vec[index]
every time) and memory allocation efficiency (avoiding a copy/move), and I suppose I'm not the only one to do such:
std::vector<A> vec;
vec.emplace_back();
A &element = vec[vec.size()-1];
element.prop = "value";
Why doesn't STL containers' emplace
, emplace_back
and emplace_front
methods return a T&
? It would allow one to write simply this rather than using a shady vec.size()-1
:
std::vector<A> vec;
A &element = vec.emplace_back();
element.prop = "value";
vector::back()
... – T.C. Jun 26 '14 at 14:23emplace_back
having avoid
return type is symmetry with the other value insertion methods, such aspush_back
. It wouldn't be too difficult to write a utility function that does theemplace_back
and returns the reference you are looking for. – Niall Jun 26 '14 at 14:26vec.emplace_back().emplace_back()
– PeterSW Jun 26 '14 at 14:30