Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how is push_back implemented in STL vector?

Tags:

c++

vector

I was asked this question in an interview.

The points I answered are like this

1) an index pointing to the current position;

2) resize if neccessary.

Can anybody elaborate more?

like image 449
skydoor Avatar asked Apr 12 '10 20:04

skydoor


People also ask

How is Push_back implemented?

Vector Push_Back() Function in C++ The dynamic array can be implemented by using a vector in C++. The elements can be added to the vector in different ways. The push_back() function is one of the ways to insert a new element at the end of the vector that increases the size of the vector by 1.

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.

Can I Push_front in vector?

You don't want to push_front on a vector ever. Adding an element to the front means moving every single other element in the vector one element back: O(n) copying.

Does Push_back copy or move?

The push_back method is used to append an element in a sequential STL container (e.g., std::vector). When inserted using the push_back, the new element is copy-or-move-constructed.


1 Answers

Like so:


void push_back(T const& param)
{
  vector temp(rbegin(), rend());
  temp.push_front(param);
  *this = vector(temp.rbegin(), temp.rend());
}
like image 189
Edward Strange Avatar answered Oct 05 '22 01:10

Edward Strange