Analysis of C ++ dynamic array Vector

Source: Internet
Author: User

 

Vector is a container in the C ++ standard template library. To put it simply, vector is a dynamic array that can store multiple types, provided that each vector can only hold one type, speaking of the list and metadata of Python, I personally think that the list of python is much easier to use than the containers of C ++ and Java. For example, JAVA supports generic programming from 1.5, it is more secure, but it still does not contain generics during compilation. The list and metadata in Python have no type restrictions. For example, I saved an integer number (python2.5) in the list, and then I saved another struct type, python has no restrictions on the Data Types in the list. Why does Python play so well? The next blog will introduce Python's built-in data types and usage, as well as some interesting bugs in Python.

1. data Structure of a vector: a vector is a continuous storage area in the memory. Its basic data structure is a sequence table. The advantage of this data structure: Fast query and quick location of an element, you don't need to traverse them one by one, but insertion is slow, because I insert an element at a certain position to move the positions of all the elements behind it, which reminds me of N-plus questions that I often talk about, for example, what is the difference between arraylist and rule list in Java. In fact, it is essentially a sequential table and a linear table of the data structure.

2. vector attributes: a vector is called a dynamic array. It can be dynamically expanded from the dynamic and array perspectives. For example, a vector has a size () method, the number of data in the returned vector is also the capacity () method, which returns the capacity of the vector. The difference between the two methods is: Like a cup, how much water size () is currently loaded (), the capacity () method can be used to load water: the code above to see how the vector is dynamically appended:

 

 
 
  1. //============================================================================  
  2. // Name        : test.cpp  
  3. // Author      : zhangpeng  
  4. // Version     :  
  5. // Copyright   : Your copyright notice  
  6. // Description : vector in C++, Ansi-style  
  7. //============================================================================  
  8.  
  9. #include<stdio.h>  
  10. #include<vector>  
  11. using namespace std;  
  12. extern "C" 
  13. typedef vector<int> vec;  
  14.  
  15. int main() {  
  16.     vec va;
  17. va.reserve(20);  
  18.     printf("va capacity %d /n",va.capacity());  
  19.     printf("va size %d /n",va.size());  
  20.     for(int i = 0; i < 30; i++){  
  21.         va.push_back(i);  
  22.     }  
  23.     printf("va capacity %d /n",va.capacity());  
  24.     printf("va size %d /n",va.size());  
  25.     return 0;  

The output result is:

Va capacity 20
Va size 0
Va Capacity 40
Va size 30

In this Code, I first set the vector capacity to 20 (applying for a cache using reserve (), which is determined based on the dynamic array inside the vector ), the size is 0, and then I append 30 elements to va. Then we can see that capacity is dynamically increasing. When the cache in the vector is not enough, it will dynamically increase its capacity by 1.5 to 2 times (in some books, it is not accurate, or the author has not written code). When it expands the cache area, first, create an empty cache area and copy the value to the new cache area. This operation reminds me of the hibernate Merge () method. This operation has drawbacks, for example, if I operate on large objects, the efficiency is not high and the basic data type is better, what should we do if we meet complex object data types? We can operate the pointer of this object, that is, the pointer stored in the vector, which will significantly improve the efficiency.

Four related member functions in vector: size () and capacity () have been introduced just now. Now let's look at reserve and resize (),

Reserve (n): forces the vector to change its capacity to at least N. If the current capacity is greater than N, zevector ignores this operation, if the current capacity is less than or equal to N, the vector is forced to be reassigned once because its capacity needs to increase.

Resize (n): if the current size exceeds the limit, the excess part is destroyed. If the current size is less than N, the default value is added.

3. Other operations of the vector member function:

C. Assign (beg, end) C. Assign (n, ELEM)

Value the data in the (beg; End) interval to C. Assign a copy of n elem values to C.

C. At (idx) // we recommend that you use this operation instead of subscript.

Returns the data indicated by the index idx. If idx is out of bounds, out_of_range is thrown.

C. Back ()

Returns the last data and does not check whether the data exists.

C. Begin ()

Returns the first data address in the iterator.

C. Clear ()

Remove all data from the container.

C. Empty ()

Determines whether the container is empty.

C. End () // points to the next of the End Element in the iterator and to a nonexistent element.

C. Erase (POS) // Delete the data at the POs location and return the next data location.

C. Erase (beg, end)

Delete the data in the [beg, end) interval and return the location of the next data.

C. Front ()

Returns the first data.

Get_allocator

Returns a copy using the constructor.

C. insert (Pos, ELEM) // insert an ELEM copy at the POs position to return the new data location

C. insert (Pos, N, ELEM) // insert n ELEM data at the POs position, no return value

C. insert (Pos, beg, end) // insert data in the [beg, end) interval at the POs position. No return value

C. max_size ()

C .~ Vector <type> memory destruction

4. Vector iterator:

Vector must support the iteration function. When talking about the iteration function, we have to describe the STL type iterator.

STL plays an important role in the iterator. The core idea of STL is to separate data structures from algorithms. The iterator exists as the bonding layer of data structures and algorithms. In STL, each container has its own iterator, while the vector iterator is a common pointer. So implementing the iteration function in vector is very simple. The Code is as follows:

 

 
 
  1. vec::iterator iter = va.begin();  
  2. int i = 0;  
  3. while(iter != va.end()){  
  4.     printf("va[%d] = %d /n ",i,*iter);  
  5.     iter ++;  
  6.     i++;  

5. Reclaim excess memory of the vector:

The purpose is to reduce the vector capacity to the required capacity:

Vector <int> (VA). Swap (VA );

To explain, we first create a copy of VA, vector <int> (VA), which is implemented through the copy constructor of vector and a copy of VA, because its copy constructor only copies the memory required by the element, the temporary VA has no excess capacity, and then the VA and VA are temporarily copied for data exchange, then, the temporary va contains unused capacity, destroys the temporary copy of the VA, and recycles excess memory. You can try (vector <int> (VA). Swap (VA). Capacity ();

Today, I am going to ask a question. Can I get the first address of the vector in addition to the iterator?

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.