STL Analysis: From Capacity () and Resize () to see the container memory allocation idea

xiaoxiao2021-03-06  61

This blog comes from a friend.

The following code wants to output 0-9, can't. The reason is that ITERSTART is actually equal to item, why?

List li; vector vi;

For (int C = 0; C <10; C ) li.push_back (c); vi.reserve (li.size ());

Copy (li.begin (), li.end (), vi.begin ());

Vector :: iterator iterstart = vi.begin (); vector :: item iterat ity = vi.end ();

Vector :: item; for (; it! = itrend; it ) {cout << * it << endl;}

-------------------------------------------------- -------

Interesting question, 2 solutions: 1) Put vi.reserve (li.size ()); modified to vi.resize;

2) Specify space at vi when constructed, il (li.size ())

The problem is to understand the reserve () function: The following is the reserve () MSDN Help: Vector :: RESERVOID RESERVE (SIZE_TYPE N); The Member Function Ensures That Capacity () Henceforth Returns At Least N. Below is a resize () MSDN Help: Vector :: Resizevoid Resize (SIZE_TYPE N, T X = T ()); The Member Function Ensures That Size () HenceForth Returns n. If IT Must LENGTHEN THE Controlled Sequence, IT Appends Elements with Value X.

The key is: reserve () has been assigned a space, but "cannot be used"! Consider the following scenario: Step1: Now size is 10 (size () and CAPACITY () return 10), retain the space of 1000 elements (using reserve ()), indicating that the space of 1000 elements after the subsection is successful, but Size () still returns 10, capenacity () returns 1000! Step2: Call Resize (100), does not reassign space (because "allocated and retained"). At this point, size () returns 100, capenacity () returns 1000!

A little Deeper: The source code for viewing STL will be easier to understand this problem. List the implementation of the size () and capacity () functions: size_type size () const {return (_first == 0? 0: _last - _first);} size_type capacity () const {return (_first == 0? 0 : _End - _first);} Note: Size () uses the _last pointer, and Capacity () uses the _end pointer! AHA! The so-called "tail pointer" has 2: _last means the tail pointer of the true data (space allowed); _end indicates the tail pointer of the space that has been assigned; Understand, IE RESERVE () and resize () distinguish. If you do not provide a reserve () method, I believe it will be easier to understand, and the price is a means of losing better memory management. Provide the purpose of the reserve () method, I understand that allows users to manually control memory allocation using Memory Pool, that is, preserved enough space (by _end control), then use the actual memory space (by _ _ LAST control)

转载请注明原文地址:https://www.9cbs.com/read-117273.html

New Post(0)