Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 484
Tryer Avatar asked Nov 19 '10 15:11

Tryer


People also ask

How do you add a value to the front of a vector?

Insert a value in v vector before the beginning. Insert another value with mentioning its size before the beginning. Print the values of v vector. Insert all values of v vector in v1 vector with mentioning the iterator of v vector.

Can we add element in vector from front?

It works alot like a std::vector but you can add and remove items from both the front and the end. It does this by dividing the internal storage up into smaller blocks. You still have random-access iterators with good lookup speed.

Can you add elements to the front of an STL vector?

vector insert() function in C++ STLstd::vector::insert() is a built-in function in C++ STL which inserts new elements before the element at the specified position, effectively increasing the container size by the number of elements inserted.


2 Answers

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.

like image 106
Stephane Rolland Avatar answered Oct 04 '22 12:10

Stephane Rolland


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.

like image 35
Mark Ransom Avatar answered Oct 04 '22 12:10

Mark Ransom