简体   繁体   中英

How does STL containers keep track of the current size of container over the total size?

Given

vector<int> a;

If a.push_back() is done, how does the vector knows whether to increase the size by reallocating memory or there is space available (Because vector allocates some extra space when size is full to reduce overhead).

PS Does same technique applies for other types of containers like stack , queue etc.

I think that it does the same thing as "struct" in C.

The method capacity() returns the number of items that can be stored in the vector without a reallocation.

The method size() returns the number of items which are currently stored in the vector.

Prior to inserting another item, it stands to reason that if size() == capacity() then more capacity will need to be made available. This will involve a reallocation to make more capacity available.

Does same technique applies for other types of containers like stack, queue etc.

stack and queue are built on top of other std containers. These underlying containers (normally vector or deque) employ a similar technique.

I think that it does the same thing as "struct" in C.

No.

In general, a vector ( and incidently a List in C# ), will allocate a block of memory. As you add elements to it, it will mark more and more of that memory as consumed. Then, when the block is full, it will allocate a new larger block, copy the contents into the new larger block, and delete the old one. Again the new larger block has more free space, and then, again, it can be filled up. The idea is that vector always has a contiguous space so it can be used in applications where one would consider an array. Because it has contiguous space, machine instructions for accessing a single element are trivial and so random access is very fast. List in C# has similar semantics. The implementation dependent thing has a lot to do with how much bigger that new bigger block is. Sometimes they make it a percentage bigger. Sometimes they just double the size.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM