Document directory
- Vector creation and traversal
- Vector Deletion
- Vector trap
- Vector element sorting
- Vector search
- Suggestions
- List Search
- List creation and traversal
- List element operations
- List sorting
- Suggestions
- Deque iterator
- Why use such a complex spatial structure?
- Deque creation and traversal
- Deque search
- Sort deque
- Suggestions
- Stack creation and traversal
- Create and traverse queue
- Searching and sorting stack/queue
- About top () and POP () of stack ()
- Suggestions
- Max heap and Min heap
- Su and Su
- Heap Formation
- Heap sorting
- Max-heap implements priority_queue
Index
- Data Structure weapon-private data center STL (on)
- Data Structure weapon-private data center STL (medium)
- Data Structure tool-private data center STL (lower)
This article http://www.cnblogs.com/daoluanxiaozi/archive/2012/12/02/confidential-stl.html due to a serious violation of the "blog garden home page" related rules, so the author changed the "private house STL" series of every article are integrated into the blog garden, cancel external links. In addition, considering the length of space,This series of articles will be divided into upper, middle, and lower. This article is "STL (I), a powerful data structure tool, and will be published in the middle and later sections. If you like it, run the following command :-)
This series of articles is suitable for beginners who want to analyze STL and want to review STL.
Students who have studied C ++ believe they have been more or less familiar with STL. STL is not only a good programming tool in C ++ (this word may be ambiguous and is more appropriate to use a class library), but also a good teaching material for learning data structures. It includes edge-length arrays, linked lists, stacks, queues, hashes, and ing. These are the core courses that computer professionals need to learn about data structures.
You must be familiar with a tool before going into it. The same is true for STL. Before analyzing STL, you can use STL first, such as vector, list, stack, and so on. It is much easier to use than analysis. Many people on the internet recommend C ++ standard library, this book is good! However, if I am a newbie and eager to learn how to use STL, I prefer to select General C ++ books (there are simple STL examples in it ). In addition, we recommend the C ++ reference site: http://www.cplusplus.com. Note: If you have read c ++ standard library, you are at most familiar with STL, but you cannot be proficient in STL.To be proficient in STL, you must do this.
To do this, you must first sharpen the tool and analyze what STL needs to do? To analyze STL, you may need to be familiar with the basic C ++ syntax and understand generic programming. Finally, STL source code analysis.
This series of articles has no intention of analyzing the specific internal implementation of STL, because there are a lot of Daniel on the Internet (@ July @ morewindows to be supplemented, their article links will be given in the corresponding article) some of the algorithms and implementations in STL have been explained in detail, so we will not be able to make an axe. Instead, this series is intended for each part in STLBriefAnd interspersed with the implementation skills.
- Vector of STL in private rooms
- List of private data centers STL
- Deque of private data center STL
- Private Data Warehouse STL stack and queue
- Heap for one minute in the private data center STL
Vector of STL in private rooms
Vector: the space of a vector can be expanded to support random access. It is a continuous linear space. Therefore, it is a dynamic space, and the array compared with it is a static space, which cannot be expanded. In short, vector is an enhanced version of the array.
Vector creation and traversal
Vector provides several versions of constructors. See: http://www.cplusplus.com/reference/stl/vector
For example:
vector<int> iv(3,3);/*3,3,3*/
Or:
......vector<int>::iterator beg = iv.begin(),end = iv.end();cout << *beg << endl;......
Vector Deletion
We do not recommend that you use the vector container where the earse () (insert operation is also the same as insert () operation is often required, because deleting elements will result in memory replication and will undoubtedly increase system overhead. In the most extreme case, delete the element of the vector header:
A B C D E F G H
B c d E F G H
B c d E F G H
Of course, there is a better way. To avoid Memory replication, during the deletion, the target to be deleted is exchanged with the element at the end of the vector before the deletion operation is executed, but this undoubtedly adds a space overhead pointing to the element at the end of the vector.
A B C D E F G H
H B c d E F G
H B c d E F G
Vector trap
It should be noted that the vector backup space is limited. When it is found that the backup space is not enough, the vector is allocated another larger space than the original space (original space * 2 ), then, the original content is moved to a new space and then the original space is released. Therefore, you must be very careful when using the iterator. After inserting elements, it is very likely that all the previously declared iterators will become invalid.
......vector<int> iv(3,3);iv.push_back(10);/*3,3,3,10*/vector<int>::iterator beg = iv.begin(),end = --iv.end();cout << iv.size() << " " << *beg << " " << *end << endl;/*4 3 10*/iv.push_back(20);cout << iv.size() << " " << *beg << " " << *end << endl;/*bomb.invalid iterator.*/......
-
Bomb !!!
Vector element sorting
#include <iostream>#include <vector>#include <algorithm>using namespace std;int main(){vector<int> iv(3,3);unsigned int i;/*add new elem.*/iv.push_back(10);iv.push_back(9);iv.push_back(0);vector<int>::iterator beg = iv.begin(),end = iv.end();/*print.*/for(i=0; i<iv.size(); i++)cout << iv[i] << " ";cout << endl;/*sort.*/sort(beg,end);/*print.*/for(i=0; i<iv.size(); i++)cout << iv[i] << " ";cout << endl;return 0;}
3 3 3 10 9 0
0 3 3 3 9 10
Press any key to continue...
Vector search
Search by traversing the elements above. The complexity is O (n ). The STL algorithm implements find (). You can find the specified element at the beginning and end of the specified iterator.
......vector<int> iv(3,3);unsigned int i;/*add new elem.*/iv.push_back(10);iv.push_back(9);iv.push_back(0);vector<int>::iterator beg = iv.begin(),end = iv.end(),ret;ret = find(beg,end,10);cout << *ret << endl;......
Suggestions
Although vector is a little better than array, it is hard to hurt, that is, when it increases dynamically, it consumes a lot of space operations, especially when there are many elements in the vector.
The vector also provides insert, earse, clear, and other element operations without retelling them one by one. Finally is a very good vector documentation: http://www.cplusplus.com/reference/stl/vector/
After this article is completed
Spoof http://www.daoluan.net/
List of private data centers STL
A list: List is a two-way circular linked list that we have touched in the data structure. The application has a Joseph ring. It can be seen that its space is non-consecutive, but it can be dynamically expanded with high efficiency, only random access is not supported. The specified element must be found through the iterator. In general, list is easy to use.
-
List_node
List Search
Search by traversing the elements above. The complexity is O (n ). The STL algorithm implements find (). You can find the specified element at the beginning and end of the specified iterator.
......list<int> il;il.push_back(5);il.push_back(98);il.push_back(7);il.push_back(20);il.push_back(22);il.push_back(17);list<int>::iterator ite;ite = find(il.begin(),il.end(),20);cout << *ite << endl;/*20*/......
List creation and traversal
STL also implements several versions of constructors for list: http://www.cplusplus.com/reference/stl/list/list/, which has the simplest features.
List traversal uses the iterator as follows:
#include <iostream>#include <list>#include <algorithm>using namespace std;int main(){unsigned int i;list<int> il;il.push_back(5);il.push_back(98);il.push_back(7);il.push_back(20);il.push_back(22);il.push_back(17);list<int>::iterator ite;for(ite = il.begin(); ite != il.end(); ite++)cout << *ite << " ";cout << endl;return 0;}
List does not experience a vector-Type Space ripple during space expansion, so as long as the element is not earse, pointing to it ite will not expire.
List element operations
List has provided pop_back, erase, clear, insert and other practical element operations, do not retell one by one, give useful documentation: http://www.cplusplus.com/reference/stl/list/
List sorting
The sort implemented by the STL algorithm (<algorithm>) is only applicable to data that supports random access, so it is not applicable to list and list does not support random access. Therefore, the List implements its own sort internally, and the internal sorting uses the fast sorting of iterative versions.
unsigned int i;list<int> il;il.push_back(5);il.push_back(98);il.push_back(7);il.push_back(20);il.push_back(22);il.push_back(17);list<int>::iterator ite;for(ite = il.begin(); ite != il.end(); ite++)cout << *ite << " ";cout << endl;il.sort();for(ite = il.begin(); ite != il.end(); ite++)cout << *ite << " ";cout << endl;return 0;
5 98 7 20 22 17
5 7 17 20 22 98
Press any key to continue...
Suggestions
The list is easy to use and cannot be accessed randomly due to the personality (not continuous) of the space.
After this article is completed
Spoof http://www.daoluan.net/
Deque of private data center STL
In one sentence, deque is a dual-end queue. Its spatial structure is not a vector-type long array, but a method of "segmented storage and overall maintenance; STL allows operations on elements (delete and add) in any position in deque (beyond the deque concept, the original deque limits the operation on elements on both ends of the queue) and allows traversal, allow Random Access (this is an illusion); we will see that deque will be the behind-the-scenes hero of stack and queue in STL, and correct deque to implement stack and queue.
-
Bug, deque_in_real
Deque iterator
The deque iterator is different from the ordinary iterator. It is not a normal pointer iterator of vector or list. It is necessary to write it down.
...... Typedef t ** map_pointer; T * cur; // points to the current element T * First; // points to the buffer header T * last; // points to the buffer tail map_pointer node; // second-level pointer, pointing to the location in the buffer address table ......
The implementation complexity is evident. It is precisely because of the complex spatial structure of deque that its iterator also wants to be complicated and obscure. So it is easy to generate an exception or!
Why use such a complex spatial structure?
Student A will ask: "Why not directly use a long array like a vector or array? In this way, the implementation is simple, and the iterator will not be like "This problem is easy to solve. Think about it: array does not need to be explained, because it is a static space and does not support expansion. In addition, in retrospect, how does a vector work to expand its space ?! Vector is compliant with the "reconfiguration, replication, and release" rule. The cost is very low. Therefore, we would rather implement complex iterators in exchange for valuable computer resources.
So how does deque perform space expansion?
If the buffer zone has a backup space, use the backup space directly. Otherwise, configure a buffer zone to record its information to the buffer address table. What's more, if the buffer address table is not enough, the buffer address table must also strictly comply with the "reconfigure, copy, release" rule, but compared to the "reconfigure, copy, releasing the "religious pursuit of fanatic vectors" rule is much more efficient.
Deque creation and traversal
In STL, deque provides constructors of multiple versions, one of which uses the default constructor.
......deque<int> id;......
Likewise, although the iterator is complex, it is easy to use and is consistent with other containers. In addition, the iterator has a heavy-load "[]" operator, therefore, "Random Access" is supported (in fact, this is an illusion. For details, refer to the above content ).
......deque<int> id;id.push_back(1);id.push_back(2);id.push_back(3);id.push_back(4);id.push_back(5);id.push_back(6);cout << id[2] << endl;/*3*/......
Deque search
Find () that can be implemented internally by STL <algorithm> (). Of course, it is also feasible to search by normal order when the "[]" operator is overloaded. Here, only the iterator version is provided:
......deque<int> id;id.push_back(1);id.push_back(2);id.push_back(6);deque<int>::iterator ite;ite = find(id.begin(),id.end(),6);cout << *ite << endl;/*6*/......
Sort deque
We already know that deque is not actually a continuous storage space. It uses the space mode of "Segment Storage, overall maintenance", and the cost is of course a complex iterator. Therefore, the sort () function of STL <algorithm> is not applicable here. Instructor Hou Jie recommended that all deque elements be moved to a vector, and then the STL <algorithm> sort () function is used to move the elements from the vector to deque. This kind of tossing is necessary and can be directly sorted within the deque, with lower efficiency.
Suggestions
Deque is rarely used in practical applications, but as stated at the beginning of the article, it is the hero behind the scenes of container stack and queue. Therefore, it is better to understand its internal implementation mechanism.
After this article is completed
Spoof http://www.daoluan.net/
Private Data Warehouse STL stack and queue
In a word, stack and queue: Compared with deque, stack and queue are not so bottom-layer. Most of their underlying operations are handled by deque. The special stack and queue are the subset of deque (in other words, stack, queue, and deque); by disabling or limiting some deque interfaces, you can easily implement stack and queue (this mechanism is called "adapter" in STL source code analysis ".); From the definition of stack and queue, their traversal actions are not allowed and there is no iterator concept. Interestingly, by modifying the list interface, similarly, the list can counterfeit stacks and queue.
-
Stack
============================
-
Queue
Stack creation and traversal
Apart from the default constructor, stack supports creating stacks based on elements in the vector, just like many other containers. Give only the default version: More Info: http://www.cplusplus.com/reference/stl/stack/stack/
.....stack<int> is;is.push(4);is.push(3);is.push(2);is.push(1);is.push(0);while(!is.empty()){cout << is.top() << " ";is.pop();}//while/*0 1 2 3 4*/.....
Stack traversal is not allowed!
Create and traverse queue
......queue<int> iq;iq.push(4);iq.push(3);iq.push(2);iq.push(1);iq.push(0);cout << iq.back() << endl;/*0*/while(!iq.empty()){cout << iq.front() << " ";iq.pop();}//while/*4 3 2 1 0*/......
The queue cannot be traversed!
Searching and sorting stack/queue
Stack/queue cannot be traversed!
About top () and POP () of stack ()
In the course of data structure, we are used to integrating the above two functions into pop, but STL is separated. One function only does one thing, and this is also done in queue.
...... Sequence C; // The underlying container ...... reference top () {return C. back ();} void POP () {C. pop_back ();}......
From the definition of sequence C, we can see some clues. Stack allows users to select the underlying container, so list can be used as the underlying container to implement stack/queue.
......stack<int,list<int>> is;is.push(4);is.push(3);is.push(2);is.push(1);is.push(0);while(!is.empty()){cout << is.top() << " ";is.pop();}//while/*0 1 2 3 4*/......
Suggestions
Stack/queue is widely used in practical applications, and the two have many commonalities. Therefore, queue is extracted. Hey, I suddenly began to respect STL.
For more information about stack and queue, see queue/
After this article is completed
Spoof http://www.daoluan.net/
Heap for one minute in the private data center STL
Heap in one sentence: a data structure, full binary tree (if the binary tree is high H, the bottom layer H is exceeded, and the other Layer 1 ~ H-1 Is full; and the bottom layer from left to right cannot have gaps .), However, in terms of implementation, it does not select a general binary tree data structure (that is, a node contains pointers pointing to two children) and uses an array; the most common operations of heap are rollback and rollback. They are often used in "maintain Heap" and "heap sorting. This article allows you to quickly review heap.
-
Full binary tree (left) and non-full binary tree (right)
========================================================== ========
-
Array Storage of A Complete Binary Tree (corresponding to the left), X is an implementation technique, deliberately empty out
If a node is located at array I, 2I is its left subnode, and 2I + 1 is its right subnode.
Max heap and Min heap
There are two types of heap: Max heap and Min heap. The maximum heap (root node) has a greater key value than all other nodes. The minimum heap (root node) has a smaller key value than all other nodes. We only discuss the maximum heap. The minimum heap and the maximum Heap have the same idea, so we will not repeat them one by one.
Su and Su
This operation is mainly used in"Push_heap"Maintain the heap nature during the process; plastic operations are often used in"Sort_heap"Maintain the heap nature during the process.
Compared with a parent node, if the key value of a node is greater than that of a parent node, the parent and child nodes are exchanged. Repeat the preceding operation until you do not need to switch or reach the root node.
-
Upstream
Bottom: this node is compared with the heap top node min (key value of the Left subnode and key value of the right subnode). If the key value of the parent node is smaller than min, that is, the parent and child nodes are exchanged. Repeat the preceding operation until there is no need to switch.
-
Downstream
Heap Formation
Task: converts an array to the maximum heap. The make_heap () function in STL can be completed. Its idea is as follows:Maintain each sub-heap from the bottom layer. Figure:
-
Make-heap
There is also a feasible idea,That is, assume that the number of elements in the heap is 0, and then push a new element to (tail end + 1) (that is, a position after the tail end, then perform the trace operation at this location. Repeat the preceding operation until all elements in the array are pushed. We found that this method is also feasible.
Heap sorting
Task: specify a maximum heap for Array sorting. The idea is straight away: because the top of the heap corresponds to the largest element swap (the top node of the heap, the rightmost node of the maximum heap). If the last node is not processed, it is traced down from the top of the heap. Note that after the next operation, the existing data is still the largest heap except the last node.
The complexity of heap sorting algorithms can reach O (nlnn), which is still very efficient in the "Sorting Algorithm family. All heap algorithms are implemented in STL <algorithm>. STL only implements the maximum heap.
......vector<int> iv(a,a+7);unsigned int i;vector<int>::iterator beg = iv.begin(),end = iv.end(),ite;for(ite = beg; ite!=end; ite++)cout << *ite << " ";cout << endl;/*1 3 9 11 21 100 4*/make_heap(beg,end);for(ite = beg; ite!=end; ite++)cout << *ite << " ";cout << endl;/*100 21 9 11 3 1 4*/sort_heap(beg,end);for(ite = beg; ite!=end; ite++)cout << *ite << " ";cout << endl;/*1 3 4 9 11 21 100*/......
Max-heap implements priority_queue
Priority_queue a queue with a weight value. After queuing, the queue is displayed according to the weight. Max-heap can meet this requirement. The top element of max-heap is always the largest. Priority_queue has vector as the underlying container in implementation, which is very different from queue.
template<class _Ty,class _Container = vector<_Ty>,class _Pr = less<typename _Container::value_type> >class priority_queue{......}
After this article is completed
Spoof http://www.daoluan.net/