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

## 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.

yes

##### 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 on other sites
Quote:
 Original post by the_eddThe 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.

## Create an account

Register a new account

• ## Partner Spotlight

• ### Forum Statistics

• Total Topics
627643
• Total Posts
2978363

• 10
• 12
• 22
• 13
• 33