Skip to main content
gamedev.net
🔒 Locked

STL again!

Started by mrmrcoleman 4 replies 1.2k views
Original Post
mrmrcoleman
mrmrcoleman
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
Enigma
Enigma
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
Agony
Agony
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 nly, and not for things themselves." - John Locke o
mrmrcoleman
mrmrcoleman
Unbelievable, that was less than a minute. Maybe Gamedev could make money by charging consultancy fees to large companies? ;)

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

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.