This blog is from a friend's question.
The following Code It cannot output 0-9. The reason is that iterstart is equivalent to iterend. Why?
List <int> Li;
Vector <int> VI;
For (int c = 0; C <10; C ++) Li. push_back (C );
Vi. Reserve (Li. Size ());
Copy (Li. Begin (), Li. End (), VI. Begin ());
Vector <int>: iterator iterstart = VI. Begin ();
Vector <int>: iterator iterend = VI. End ();
Vector <int>: iterator it = iterstart;
For (; it! = Iterend; it ++)
{
Cout <* It <Endl;
}
---------------------------------------------------------
Interesting question: two solutions:
1)
Vi. Reserve (Li. Size ());
Change
Vi. Resize (Li. Size ());
2) Specify the space during construction
Vector <int> VI (Li. Size ())
The problem lies in the understanding of the Reserve () function:
The following is the msdn help of reserve:
Vector: Reserve
Void reserve (size_type N );
The member function ensures that capacity () henceforth returns at least N.
The following is the msdn help of resize:
Vector: resize
Void 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 that the reserve () has been allocated space, but "cannot be used "! Consider the following scenarios:
Step 1: The current size is 10 (SIZE () and capacity () returns 10), retain the space of 1000 elements (using reserve ()), it indicates that the space of the next 1000 elements has been allocated successfully, but size () still returns 10, capacity () returns 1000!
Step 2: Call resize (100) and there is no actually re-allocated space (because "allocated and retained" is 1000 ). In this case, size () returns 100 and capacity () returns 1000!
A little deeper: View STL's Source code It is easier to understand this problem. List the implementation of the size () and capacity () functions of a vector:
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, while capacity () uses the _ end pointer!
Aha! The so-called "tail Pointer" has two:
_ Last indicates the tail pointer of the real data (space allowed;
_ End indicates the end pointer of the allocated space;
I. e.
The difference between reserve () and resize. If the reserve () method is not provided, it is easier to understand, at the cost of losing a better means of memory management. Provide
The purpose of the reserve () method is to allow users to use memory.
The pool idea is used to manually control the memory allocation, that is, reserve enough space (controlled by _ end) in advance, and then use the actual memory space (controlled by _ last) as needed)