1. c ++ STL has been widely praised and used by many people. It not only provides convenient containers such as vector, string, and list, more importantly, STL encapsulates many complex data structure algorithms and a large number of common data structure operations. Vector encapsulation array, list encapsulation chain table, MAP and set encapsulation Binary Tree, etc.
2. The standard associated containers set, Multiset, map, and multimap use a very efficient binary tree for balanced search: The red and black trees have also become the red-black trees ). The statistical performance of the RB tree is better than that of the normal balanced binary tree.
3. The use of STL map and set is not complex, but it is difficult to understand, such:
Map: Type pair <const key, T>: a set of T objects corresponding to many different const keys. All record sets can be changed as long as the const key is different. t is irrelevant!
Set: Type const key. Only a single pair of const key is saved, and T pairs without map are saved! It can be seen as a special case of map.
(1) Why is the insert/delete efficiency of MAP and set more efficient than other sequential containers ?, Tree
A: For associated containers, memory copying and memory moving are not required. That's true. All elements in the map and set containers are stored as nodes. The node structure is similar to the linked list, pointing to the parent node and the child node.
·
(2) Why does the previously saved iterator not expire after each insert operation?
A: iterator is equivalent to a pointer to a node. If the memory does not change, how can the pointer to the memory become invalid? (of course, the deleted element has already expired ). The pointer may be invalid for each deletion or insertion of a vector, and push_back is called to insert data at the end. To ensure the continuous storage of internal data, the block pointed to by iterator may have been overwritten by other memory or the memory has been released. Even when push_back is used, the internal space of the container may be insufficient and a larger memory is required. Only the previous memory is released and a larger memory is applied, copy the existing data elements to the new memory, and put the elements to be inserted at the end, so the previous memory pointer is naturally unavailable. Especially when using algorithms such as find, remember this principle: Do not use expired iterator.
(3) Why cannot map and set have a reserve function like a vector to pre-allocate data?
A: I used to ask this question. In terms of its principle, the reason is that the nodes stored in the map and set are not the elements themselves, but the nodes containing the elements. That is to say, the alloc used inside the map is not the alloc passed in from the parameter when the Map <key, Data, compare, alloc> is declared. For example:
4. Set, Multiset
Set and Multiset will automatically sort the elements according to specific sorting rules. The elements in the set cannot be repeated, and the Multiset can be repeated.
The elements in the set cannot be modified because they are sorted. They can only be deleted before being added.
The element type added to the set must be reloaded. The <operator is used for sorting. Sorting meets the following criteria:
1. Asymmetric. If a <B is true, B <A is false.
2. It can be passed. If a <B, B <C, A <C.
3. A <A is always false.
Set to determine whether the elements are equal:
If (! (A <B | B <A) When both a <B and B <A are false, they are equal.
5. Map, multimap
Map and multimap use the pair composed of key and value as elements. The elements are automatically sorted according to the key sorting rules. The keys of elements in map cannot be repeated, and multimap can be repeated.
Map <key, value>
Because the elements are sorted, the keys of the elements in the map cannot be modified and can only be deleted before being added. The value corresponding to the key can be modified.
The key type of the elements added to the map must be overloaded. The <operator is used to sort the elements. The sorting is consistent with the set rule.
6. Functions and methods of list
There are actually two types of list: one is the basic arraylist, which has the advantage of random access elements and the other is the more powerful random list, which is not designed for fast random access, instead, it has a set of more general methods.
List: Order is the most important feature of list: it ensures that the specific order of elements is maintained. List adds many methods to the collection so that elements can be inserted and removed from the List (this is only recommended for using the list .) A list can generate listiterator, which can be used to traverse the list in two directions, or to insert and remove elements from the list.
Arraylist: List implemented by arrays. Quick and Random Access to elements is allowed, but it is slow to insert and remove elements into the list. Listiterator should only be used to traverse the arraylist from the forward, rather than to insert and remove elements. This is much higher than the overhead of the shortlist.
Optimize list: the sequential access is optimized, and the overhead of insert and delete to the list is not large. Random Access is relatively slow. (Use arraylist instead .) The following methods are available: addfirst (), addlast (), getfirst (), getlast (), removefirst (), and removelast (), these methods (not defined in any interface or base class) Enable the queue list to be used as a stack, queue, and bidirectional queue.
7 .. 1 what is the difference between hash_map and map?
Constructor. Hash_map requires the hash function, which is equal to the function; map only needs the comparison function (less than the function ).
Storage Structure. Hash_map uses hash table storage, and map generally uses the red/black tree (rb tree. Therefore, the memory data structure is different.
7.2 When do I need hash_map and map?
In general, the query speed of hash_map is faster than that of map, and the basic search speed and data volume size belong to the constant level, while that of map is log (n) level. Not necessarily, constants are smaller than log (n), and the time consumption of hash functions is also time-consuming. See, if you consider efficiency, especially when the number of elements reaches a certain order of magnitude, consider hash_map. However, if you are very strict with the memory usage and want the program to consume as little memory as possible, be careful. hash_map may embarrass you, especially when you have many hash_map objects, you cannot control it, and the construction speed of hash_map is slow.
Do you know how to choose? Weigh three factors: search speed, data volume, and memory usage.
8. Some Usage suggestions:
Level 1-only used as map: uses static Arrays
Level 2-Save the fixed-length data and traverse all data during use: Use a dynamic array (static array can also be used if the length is fixed at the beginning)
Level 3-the ability to dynamically increase the storage length of an array, focusing on data search speed: Using Vector
Level 3-the ability to dynamically increase the storage duration of an array, focusing on increasing the speed of data deletion: Using list
Level 4-complex operations on data, that is, the ability to add and delete data before and after, and a good data access speed: deque
Level 5-there are many addition and deletion operations on the data center: Using list, we recommend that you batch add and delete operations on the basis of sorting to maximize the running efficiency.
Level 6-none of the above can be found: Combine STL containers or build a special data structure by yourself.
9.
(1). Vector-Automatically increasing array
Vector <int> VEC (10) // a container with 10 int Elements
Vector <float> VEC (10, 0.5) // a container with 10 float elements and their values are all 0.5
Vector <int>: iterator ITER;
For (iter = Vec. Begin (); iter! = Vec. End (); ITER ++)
{
//.......
}
Vector can only forward as the array grows. Therefore, it only provides backend insertion and deletion,
That is, push_back and pop_back. Of course, you can also operate data on the front end and in the middle,
Insert and erase are used, but operations on data in the front end and in the middle will inevitably lead to the movement of data blocks,
This has a very high impact on performance.
The biggest advantage is the random access capability.
Vector <t1 >:: iterator related methods include:
Begin (): used to obtain a pointer pointing to the first element of the vector.
End (): used to obtain a pointer to the position after the last element of the vector. Note that it does not point to the last element.
Erase (vector <t1 >:: iterator): Used to delete the element pointed to by the iterator passed in as a parameter.
(2). List-good at inserting deleted linked lists
List <string> milkshakes; List <int> scores;
Push_back, pop_back push_front. pop_front
List is the implementation of a two-way linked list.
To provide bidirectional traversal, the List has two more pointers to the front and back of the normal data unit.
An example of using iterator to delete Elements
List <string> stringlist;
List <string >:: iterator ITER;
Advance (ITER, 5); // point iterator to the fifth element of stringlist
Stringlist. Erase (iterator); // Delete
After the delete operation is complete, where does the iterator that passes in the erase () method point? It points to the last element of the element pointed to before the delete operation.
(3). deque-Dual-end queue with the advantages of vector and list
(4). Summary and comparison of the three templates and general usage guidelines
These three templates belong to the sequence class template. We can see that they have some common methods.
Size (): Get the container size.
Begin (): Get the pointer to the first element in the container (the pointer type varies with the container)
End (): Get the pointer pointing to the position next to the last element in the container
Erase (): deletes the element pointed to by the incoming pointer.
Clear (): Clear all elements
= Operator: determines whether two containers are equal
= Operator: used to assign values to containers
The preceding three templates have their own characteristics.
The data in the Vector Template is arranged continuously in the memory, so the random access elements (that is, access through the [] Operator) are the fastest, which is consistent with the array. Similarly, due to its continuous arrangement, it is very slow to delete or add elements outside the tail. This operation should be avoided when vector is used.
The data in the list template is chained, so elements cannot be randomly accessed. It has the advantage of adding and deleting elements at any location.
The deque template is implemented by linking several pieces of continuous data, so the features of the above two containers are balanced.