Samaursa
Samaursa

Reputation: 17197

Why don't the push_back in vector<> and list<> containers return the reference to the inserted element?

I realize I can get the iterator reference by calling back() but why not return it with push_back() as well? Is it for performance reasons? Or is it due to exception safety (similar to why pop_back() doesn't return the popped value)? In either case, please explain.

Upvotes: 18

Views: 4138

Answers (3)

Nicol Bolas
Nicol Bolas

Reputation: 473322

Various insert functions return an iterator for a very simple reason: the caller does not necessarily know how to get an iterator to that element. map::insert and set::insert return one because otherwise, the caller would have to search for the element.

When you do a vector::push_back, you know where the inserted element is. It's --vector.end(). You don't have to search for it; it's always that location. You can get it in constant time, and pretty quick constant time at that.

So there's really no point in returning something that the user already knows.

Upvotes: 20

Mark B
Mark B

Reputation: 96241

The reason is that vector provides an insert method that does return an iterator to the inserted position. The standard is consistent in that push_back doesn't return a value but some forms of insert will, when available and appropriate.

Upvotes: 0

JaredPar
JaredPar

Reputation: 754645

I don't know if there is an official reason but the most immediate that comes to my mind is performance. If you look at the majority of uses of push_back and push_front the return value is not used. Where an element is pushed is not so important as that it's pushed.

Why return a non-free value that is almost never used?

Upvotes: 3

Related Questions