I write for yourself Implementing the vector container. And I can not understand the principle of work and that Methods do generally. Vector :: Capacity () and vector :: reserve (). I read the documentation, but I do not understand anything.
Answer 1, Authority 100%
The fact is that there is a simple dynamic array inside the vector (this should be obvious, but I will refine it yet), to which you can even get a pointer via
Vector: data () . In this case, the vector allows you to almost unlimited add data to it (until the memory is over). How does he do it? Also, as you would be done with a dynamic array: requests a larger memory block at the OS, it copies all the current data there, adds new data to there and frees the old memory block.
But there is one feature: if the memory in the current block is over and you want to add data, it requests a new memory block much more than necessary (for example, two times more than it is now, and not n + 1, where N is the current number of elements in vector). What for? Imagine that you need to add a lot of elements in the cycle to the end of the vector. Imagine how slow it will work if on each iteration will have to re-release the memory on N + 1 elements, then it’s all copied, in short, horror. And if you request a lot of memory right away, then you will have to replace memory much less frequently.
Here, of course, it is important to observe the measure so that there are no many unused memory. I do not know honestly, for what strategy, the various realization of the vector calculate the size of the memory, which must be allocated, but it seems to me so that it is 2 times more memory every time than it is quite optimal. GCC It seems like this and makes .
Now directly go to the question.
Vector :: Capacity () shows how many elements the vector can accommodate without memory statements, while
vector :: Size () shows how many elements are stored in the current moment. It is clear that
vector :: Size () will be less or equal to
Vector :: Capacity () .
Vector :: Reserve (Size_Type N) Says the vector to highlight enough memory for storage minimum n elements, that is, this function changes
Vector :: Capacity ()