Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ vector resize elements re-ordered?

Tags:

c++

vector

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?

like image 329
Adrian Diaz Avatar asked Jul 08 '18 07:07

Adrian Diaz


People also ask

What happens to the elements in a vector when it is resized to something bigger smaller?

vector::resize() It happens so, If the given value of n is less than the size at present then extra elements are demolished. If n is more than current size of container then upcoming elements are appended at the end of the vector.

What happens to a vector when it is resized?

The C++ function std::vector::resize() changes the size of vector. If n is smaller than current size then extra elements are destroyed. If n is greater than current container size then new elements are inserted at the end of vector. If val is specified then new elements are initialed with val.

Is all data stored in a vector lost when resized?

Vector images don't use pixels. They're created with mathematical equations, lines, and curves — using points fixed on a grid — which means images can be made infinitely larger (or smaller) without losing resolution. Basically, vectors don't lose quality when resized.

Does vector clear reset size?

vector::clear() clear() function is used to remove all the elements of the vector container, thus making it size 0.


1 Answers

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.

like image 101
StoryTeller - Unslander Monica Avatar answered Nov 15 '22 06:11

StoryTeller - Unslander Monica