Sign in to follow this  

Will std::vector preserve the index order when just accessing and pushing items?

This topic is 3415 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

Will std::vector preserve the index orders of the elements if all I do with it is access the elements through an iterator and add elements to the end using push_back, never sorting the vector or deleting items from it. (i.e. will myVector[c] always point to the same element in this case?) I'm pretty sure the answer is yes, but I'd like to get assured of it. For some reason I couldn't find a definite answer from the STL references. Thanks for the answers.

Share this post


Link to post
Share on other sites
The order of elements are preserved, but the locations (addresses) aren't.

You shouldn't do something like this:


std::vector<int> numbers;

numbers.push_back(1);
numbers.push_back(2);
numbers.push_back(3);
numbers.push_back(4);

int *p = &numbers[1];

numbers.push_back(5);

*p = 6; // bad


When you call push_back(), the vector may not have enough memory allocated to append the element. In this case it will reallocate a new block and copy the existing elements in before tacking on the element to be push_back-ed. This means that any pointers, references or iterators referring to elements of the vector before the push_back will now point in to no-mans land -- the old block of memory, which will have been released and returned to the OS/allocator for other purposes.

Share this post


Link to post
Share on other sites
Quote:
Original post by the_edd
The order of elements are preserved, but the locations (addresses) aren't.

Unless the original capacity is sufficient to store the new number of vector elements. If capacity() is greater than size(), then push_back() is guaranteed to not shuffle the elements around in memory.

Share this post


Link to post
Share on other sites

This topic is 3415 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