6

If my vector starts out with some information in it such as:

vector<int> ordered_set; ordered_set.resize(5); for (int counter=0; counter<5; counter++){ ordered_set[counter]=counter+1; } 

Then I later resize it as:

ordered_set.resize(10,0); 

will the 1 through 5 still be guaranteed as the first five elements through the pointer arithmetic ordered_set[0,1,2..4]? or does the standard enable the contents to permute if contiguous memory is not found for the resize and a reallocation is required? In other words will ordered_set[0,1,2..4] potentially encounter a 0?

1
  • 1
    Only if you sort the vector (to order, so elements with zero value occur before the others) after resizing the second time. Commented Jul 8, 2018 at 11:57

2 Answers 2

7

A std::vector is defined as a contiguous container of elements. If the vector's allocator cannot provide enough memory when resizing, the vector won't "fracture". It cannot maintain its invariant so the operation simply won't finish, on account of an exception being thrown.

As for pointer arithmetic, you can be sure that traversing the vector after resizing will produce the same integer values you previously placed there. But be sure to not use any pointers or iterators you obtained prior to resizing, as those would have become invalid.

Sign up to request clarification or add additional context in comments.

Comments

0

See the description of vector::resize at https://en.cppreference.com/w/cpp/container/vector/resize

It states: 'additional ... elements are appended'. This, to my understanding of the verb 'to append', implies that permutations or positional moves of existing elements are not allowed.

1 Comment

Yea at face value that was my first impression too; my confusion was mostly related to the suggested use of pointer arithmetic on the object name, further convoluted by the description of iterators being invalidated after a reallocation. I'm only used to the idea of using x[m] when x is a pointer rather than an object name.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.