Recommended Posts

Ok, just to clear up the functionality of insert.
If I do this...
vector<int> Vec1;
fill Vec1, with 1,2,3,4,5.
Then..
Vec1.insert(Vec1.begin(), 3);
Will I then end up with
3,1,2,3,4,5?
i.e. Is this the same functionality as a push_front on a list?
Thank again.
Mark

0

Share this post

Link to post

Share on other sites

Yes. insert will insert the element directly infront of the given iterator, so if the given iterator is the front of the vector the behaviour is identical to push_front. Also note that this operation is highly inefficient for vectors, since it involves moving the entire contents of the vector, which is why vector does not provide a push_front member function.

Enigma

0

Share this post

Link to post

Share on other sites

Correct. .insert() will insert the item before the iterator you give it. However, if you are going to do a lot of inserts at or near the beginning of the vector, it might not be the container you should really be using. A possible alternative would be a deque. It's very similar, has random access, but can handle inserting at the beginning just as well as at the end, I believe.

Share this post

Link to post

Share on other sites

Basically the same except that to insert into the front of a vector, all the data in the vector has to be copied and moved (handled automatically, but still slow). Inserting to the back is very fast unless the vector's size is equal to its capacity, then all the data needs to be moved.