Sign in to follow this  

STL again!

This topic is 4486 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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

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

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.

Share this post


Link to post
Share on other sites
Quote:
Original post by Agony
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.


Remember though that the data is not contiguous and cannot be used where a function expects a C style array.

Share this post


Link to post
Share on other sites

This topic is 4486 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this