当前位置:网站首页>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 .
边栏推荐
- Jsonp processing non homologous
- Applet password input box
- <C>. Rolling phase division
- 一、HikariCP获取连接流程源码分析一
- Dependency injection in PHP reflection implementation framework
- Print 1 cute every 100 milliseconds ~ with a running lantern effect
- Is it safe to open a new bond securities account
- Profile path and name
- Uniapp waterfall flow, applet waterfall flow, very simple, suitable for the whole platform
- C language PTA -- continuity factor
猜你喜欢
Determine whether it is a web page opened on wechat
mysql load data infile
Ali vision AI training camp-day01
Automatic fitting when the applet reaches the top
Web components - Basics
Vulnhub range - darkhole 1
Yaml configuration
Vulnhub range - the planes:venus
Verification code native JS canvas
Bloom filter
随机推荐
1、 Hikaricp source code analysis of connection acquisition process I
打新债证券开户安全吗
3、 Hikaricp source code analysis of connection acquisition process III
Using flex to implement the Holy Grail layout is as simple as that
2.17(Avoid The Lakes)
2.5 find the sum of the first n terms of the square root sequence
Case: count the most characters and times
Applet Click to return to the top 2 methods
Two types of attribute injection methods
Browser performance optimization (19)
RPM package installation command
<C>. Calculation date to day conversion
rmi-registry-bind-deserialization
三、HikariCP获取连接流程源码分析三
Est - il sûr d'ouvrir un compte avec de nouvelles dettes? Une faible Commission est - elle crédible?
Can GoogleSEO only do content without external chain? (e6zzseo)
ECS 7-day practical training camp (Advanced route) -- day03 -- ecs+slb load balancing practice
PAT B1071
CG kit explore high performance rendering on mobile terminal
Principles of MySQL clustered index and non clustered index