Differences, how vector::reserve() and vector::capacity work()

I am writing an implementation of the vector container for myself. And I can't understand how it works and what the vector::capacity() and vector::reserve () methods do in general. I read the documentation, but I don't understand anything.

 2
Author: Oleg_Hudyma, 2017-04-07

1 answers

The fact is that a simple dynamic array is used inside the vector (this should be obvious, but I'll clarify all the same), to which you can even get a pointer via vector:data(). At the same time, the vector allows you to add data to it almost indefinitely (until the memory runs out). How does he do it? Just like you would do with a dynamic array: requests a larger block of memory from the OS, copies all the current data there, adds new data there, and frees the old block of memory.

But there is one feature: if the memory in the current block has run out and you want to add more data, it requests a new block of memory much larger than necessary (for example, twice as large as it is now, and not N+1, where N is the current number of elements in the vector). What for? Imagine that you need to add many, many elements to the end of the vector in a loop. Imagine how slow it will be if you have to reallocate the memory by N+1 at each iteration elements, then it's all copy more, in short horror. And if you request a lot of memory at once, then you will have to re-allocate memory much less often.

Here, of course, it is important to observe the measure so that there is not a lot of unused memory. I do not honestly know what strategy the different vector implementations use to calculate the amount of memory to allocate, but it seems to me that allocating 2 times more memory each time is quite optimal. GCC seems to do this and does.

Now I will go directly to the question. vector::capacity() shows how many elements the vector can hold without reallocating memory, whereas vector::size() shows how many elements are currently stored in the vector. It is clear that vector::size() will be less than or equal to vector::capacity(). vector::reserve(size_type N) tells the vector to allocate enough memory to store at least N elements, that is, this function modifies vector::capacity().

 5
Author: Flowneee, 2017-04-07 20:55:06