当前位置:网站首页>III Implementation principle of vector
III Implementation principle of vector
2022-06-25 20:01:00 【Xiaohong_ coding】
List of articles
- One .vector Implementation principle of
- 1.vector Base class introduction
- 2.vector What happens when you insert elements from the back
- 3.vector What happens when you insert an element in the middle
- 4.vector Delete element memory will be released
- 5.vector How to modify the element value of a certain position
- 6.vector The time complexity of reading and inserting elements
- 7.vector Basic algorithm
- 8.vector Summary of the underlying implementation
- Two .vector Precautions for
Review tips : For the convenience of reading , I didn't add the source code , If you want to know more , You can see Mr. Houjie's STL Source analysis . This is a summary for the students who have read this book , Just recite it directly .
One .vector Implementation principle of
1.vector Base class introduction
vector Is a template class , Its base class does nothing
vector<int> v;Such a statement , It just calls the parameterless construction of the base class , It did nothing . There is no dynamic allocation of memory .If vector Specify container size at construction time , Then dynamic memory will be applied when declaring , But if the construct is the default construct , It doesn't apply for dynamic memory .
The role of base classes :
- Save container start position 、 The end location and the next location of the requested memory space ;
- Apply for dynamic memory space .
2.vector What happens when you insert elements from the back
Assign an element as 1 Space , Insert this element , If the back exceeds the space requested by the container , Reallocate a new memory space ( Its size is the size of the original space 2 times ).
Copy all the elements of the original memory to the new memory in the same order , And insert the element to be inserted into the next position of the last element .
Call the destructor in the original memory , Destroy original memory .
3.vector What happens when you insert an element in the middle
- In fact, it is to move the element behind the current position of the element to be inserted backward , Then insert the element to be inserted into the corresponding position .
4.vector Delete element memory will be released
- The last deletion from the container is to call pop_back(), Move the iterator forward one bit , Then destroy the last element .
- What removes the call from the middle of the container is erase( The function is to delete the element in the current position , Move the following elements of the deleted element forward one bit in turn , And returns the iterator pointing to the current position ). So deleting an element from the middle will not release the dynamic memory that has been requested
5.vector How to modify the element value of a certain position
- vector You can modify the value of the current element by means of iterators and subscripts .
6.vector The time complexity of reading and inserting elements
- vector Read an element , You can take at, as well as [] To access elements directly , So the time complexity of reading elements is O(1), Inserting and deleting elements requires moving elements , The time complexity is O(n). The time complexity of inserting and deleting elements at the end is O(1).
7.vector Basic algorithm
because vector have operator *,operator ++,operator --,operator +=,operator -=,operator -,operator +,opeator->, therefore vector Our iterators are random access iterators .
pop_back(), push_back() Deletion at the end , Tail insertion
erase Delete... In the specified location
clear Delete all
insert Insert... At specified location
[] , at[] visit , Modifying elements
8.vector Summary of the underlying implementation
- vector It's a dynamic array , Used to maintain a continuous dynamic control , There are three member functions inside , Used to store the starting position , Used position , And the last position , Whenever dynamic memory runs out , It will follow the original memory 2 times , Reapply for new memory . Copy the data from the original memory to the new memory , Free the original memory .
Two .vector Precautions for
1. Use... In uncertain situations at instead of operator[]
- at Will check if it's out of bounds , Suppose you are not sure whether the current access action will cross the boundary
2. What type can't be used as vector The template type of
- about vector Template specialization types , Because in vector During the implementation of , Variables are often copied or assigned values , therefore vector The template type of should have a public copy constructor and overloaded assignment operator functions .
3. vector The reason why the iterator of will fail
The space pointed to by the corresponding pointer at the bottom of the iterator is destroyed , And use a space that has been released , The consequence is that the program crashes ( That is, if you continue to use an iterator that has expired , The program could crash ).
An operation that causes a change in its underlying space , It is possible that the iterator fails , such as :resize、reserve、insert、assign、 push_back etc.
stay vector Delete elements in the middle of the container according to the specified iterator , That is to call erase function , At this time, because the current position will be covered by the following elements , So the specified iterator will fail , But at this point you can go through erase Gets the correct iterator for the current position ;
stay vector When you need to re apply for memory , Such as capacity , For example, in the process of releasing unused memory and so on, the problem of iterator failure will occur , Because the memory has changed , At this point, you need to regain the iterator ;
4. vector How to release memory quickly
Some people say it can be called reserve(0) To release , After all reserve Function will reapply the memory according to the size we specified , That won't work , This function will only act when the size of the input memory is larger than the original memory , Otherwise, no action will be taken .
As for passing resize perhaps clear It doesn't work , These functions only destruct all elements that are currently stored in the container , But the memory space of the container itself will not be released .
4.1 adopt swap function
Now we can think about , Under what circumstances vector The size is 0 Well , As an empty container , So to release memory quickly , We can refer to swap Function mechanism , Use an empty vector With the current vector swapping , Use form like
vector<int>().swap(v)This code , take v This vector The memory space represented by the variable is the same as an empty vector swapping , such v The memory space of is equal to be released , And this empty vector Because it's a temporary variable , It's at the end of this line of code , Automatically called vector The destructor of frees up dynamic memory space , such , One vector The dynamic memory is quickly released .4.2 Use shrink_to_fit function
Its function is to free up unused memory , Suppose we call clear Function cleans out all the elements , Is the whole container unused , Then call shrink_to_fit Function to free up unused memory , Let's take this one vector Is the memory free .
边栏推荐
- Applet multi image to Base64 upload
- Wechat applet swiper simple local picture display appears large blank
- Curtain down and departure
- PHP FPM, workman, spoole, golang simple performance test
- Appearance of object attributes
- Process of vacuum and vacuum full
- Yum command
- Wechat applet connects to the server to display mqtt data information
- What are Baidu collection skills? 2022 Baidu article collection skills
- 5、 Initialization analysis II of hikaricp source code analysis
猜你喜欢

PHP synchronizes website content to hundreds of websites to improve SEO ranking

JS asynchronism (I. asynchronous concept, basic use of web worker)

ECS 7-day practical training camp (Advanced route) -- day01 -- setting up FTP service based on ECS

rmi-registry-bind-deserialization

Pta--7-20 exchange minimum and maximum (15 points)

CG kit explore high performance rendering on mobile terminal

String since I can perform performance tuning, I can call an expert directly

wooyun-2014-065513

New features of php7

Can GoogleSEO only do content without external chain? (e6zzseo)
随机推荐
Jsonp function encapsulation
通过启牛学堂开的股票账户可以用吗?资金安全吗?
Wechat applet cloud function does not have dependency option installed
<C>. String comparison
PostgreSQL division considerations
Single chip microcomputer line selection method to store impression (address range) method + Example
Does GoogleSEO need to change the friend chain? (e6zzseo)
Redis cache preheating & avalanche & breakdown & penetration
2.5 find the sum of the first n terms of the square root sequence
JS asynchronism (III. usage of generator and async/await)
Vulnhub range the planes:earth
PHP little knowledge record
Pat b1054 average (20 points)
Panda weekly -2022/02/18
Process of vacuum and vacuum full
Pdf file download (the download name is the same as the file name)
Browser performance optimization (19)
5、 Initialization analysis II of hikaricp source code analysis
ECS 7-day practical training camp (Advanced route) -- day03 -- ecs+slb load balancing practice
Ali visual AI training camp -day05- creativity day - your image recognition project