Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 876
Samaursa Avatar asked Jan 23 '12 16:01

Samaursa


People also ask

What does Push_back do in a vector?

push_back() function is used to push elements into a vector from the back. The new value is inserted into the vector at the end, after the current last element and the container size is increased by 1. 1.

Is Push_back by reference?

Yes it is correct that the object is passed by reference to the push_back function. Inside the function a copy is made that is stored in the vector.

What does Push_back mean in C++?

The push_back() function is used to insert an element at the end of a vector.

Can we use Push_back in array?

The push_back() method is typically , provided there is adequate capacity in the underlying array.


1 Answers

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.

like image 118
Nicol Bolas Avatar answered Sep 23 '22 00:09

Nicol Bolas