Inserting into a vector at the front

iterator insert ( iterator position, const T& x );

Is the function declaration of the insert operator of the std::Vector class.

This function's return type is an iterator pointing to the inserted element. My question is, given this return type, what is the most efficient way (this is part of a larger program I am running where speed is of the essence, so I am looking for the most computationally efficient way) of inserting at the beginning. Is it the following?

//Code 1
vector<int> intvector;
vector<int>::iterator it;
it = myvector.begin();
for(int i = 1; i <= 100000; i++){
    it = intvector.insert(it,i);
}

Or,

//Code 2
vector<int> intvector;
for(int i = 1; i <= 100000; i++){
    intvector.insert(intvector.begin(),i);
}

Essentially, in Code 2, is the parameter,

intvector.begin() 

"Costly" to evaluate computationally as compared to using the returned iterator in Code 1 or should both be equally cheap/costly?


If one of the critical needs of your program is to insert elements at the begining of a container: then you should use a std::deque and not a std::vector. std::vector is only good at inserting elements at the end.

STL diagram for choosing containers

Other containers have been introduced in C++11. I should start to find an updated graph with these new containers and insert it here.


The efficiency of obtaining the insertion point won't matter in the least - it will be dwarfed by the inefficiency of constantly shuffling the existing data up every time you do an insertion.

Use std::deque for this, that's what it was designed for.


An old thread, but it showed up at a coworker's desk as the first search result for a Google query.

There is one alternative to using a deque that is worth considering:

std::vector<T> foo;
for (int i = 0; i < 100000; ++i)
  foo.push_back(T());
std::reverse( foo.begin(), foo.end() );

You still use a vector which is significantly more engineered than deque for performance. Also, swaps (which is what reverse uses) are quite efficient. On the other hand, the complexity, while still linear, is increased by 50%.

As always, measure before you decide what to do.


Most likely deque is the appropriate solution as suggested by others. But just for completeness, suppose that you need to do this front-insertion just once, that elsewhere in the program you don't need to do other operations on the front, and that otherwise vector provides the interface you need. If all of those are true, you could add the items with the very efficient push_back and then reverse the vector to get everything in order. That would have linear complexity rather than polynomial as it would when inserting at the front.


If you're looking for a computationally efficient way of inserting at the front, then you probably want to use a deque instead of a vector.