STL again!

Started by
4 comments, last by Qw3r7yU10p! 18 years, 8 months ago
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
Advertisement
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
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.
"We should have a great fewer disputes in the world if words were taken for what they are, the signs of our ideas only, and not for things themselves." - John Locke
Unbelievable, that was less than a minute. Maybe Gamedev could make money by charging consultancy fees to large companies? ;)

Thanks, Enigma.
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.
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.

This topic is closed to new replies.

Advertisement