STL map details

Source: Internet
Author: User
Analysis of map usage in STL [full version]

1 Map Overview
STL (Standard Template Library) is the core of the C ++ standard library, which profoundly affects the overall structure of the standard library. STL is a general library that provides a series of software solutions and uses advanced and efficient algorithms to manage data. The advantage of STL is that it encapsulates many data structures and algorithms (algorithm), and map is a typical example.
Map is an associated container of STL. It provides one-to-one (the first key/value can be called a keyword, and each keyword can only appear once in map, the second value can be called the value of this keyword) is the data processing capability. Due to this feature, you can provide a quick channel for programming when processing one-to-one data.
2 Map usage
Assume that each student's student ID and his/her name have a one-to-one ing relationship in a class. This model can be easily described using map. The student ID is described using int and the name is described using strings, the following code describes the map: Map <int, string> mapstudent.
2.1 Insert data
You can perform the following operations to insert a map element:
The first method is to obtain the elements in the map through the primary key. If the elements are obtained, the real values (objects stored in the map node) corresponding to the corresponding node are returned ). However, this method produces side effects. If the real value of the node is obtained using the primary key "key" and this node does not exist in the map, the node with the key as the primary key will be directly inserted into the map, and return this node. In this case, you can assign values to it. However, if a node with the key as the primary key exists in the map, the actual value of the node is returned. If the node is copied at this time, the original node may be overwritten by the new node, if the pointer type is used, memory leakage and other problems may occur. We do not recommend using this method to insert elements because of this side effect.
The second type inserts value_type data.
Insert method interface prototype: pair <ierator, bool> insert (const value_type & X)
This method needs to construct a key-value pair, that is, value_type, and then call the insert method to find the corresponding node based on the key value in the key-value pair, then, the current node is not inserted, the node found is returned, and the second number in the pair is set to false; otherwise, the current node is inserted and the inserted current node is returned, and the second value is set to true. When inserting a node, a new value_type node is re-constructed inside the map and the input x is copied. The placement new method is used internally, allocate a map node through the memory distributor, and then call the value_type constructor in the obtained Node space. Therefore, value_type, a key-Value Pair constructed by the caller, is a temporary variable and will not be added to the map (do not be confused by the reference operator. Here we only consider parameter transfer efficiency ). This method of node insertion is safe. We recommend that you insert elements to the map, determine the returned Insert Results, and perform subsequent processing based on the inserted results.
# Pragma warning (Disable: 4786)
# Include <map>
# Include <string>
# Include <iostream>
Using namespace STD;
Int main ()
{
Map <int, string> mapstudent;
Mapstudent. insert (Map <int, string >:value_type (1, "one "));
Mapstudent. insert (Map <int, string >:value_type (2, "two "));
Mapstudent. insert (Map <int, string >:value_type (3, "three "));
Map <int, string >:: iterator ITER;
For (iter = mapstudent. Begin (); iter! = Mapstudent. End (); ITER ++)
{
Cout <ITER-> first <"" <ITER-> second <Endl;
}
}
2.2 map size
After inserting data into the map, you can use the size () function to obtain the number of data already inserted:
Int nsize = mapstudent. Size ()
2.3 sorting
By default, STL uses less than signs for sorting. The above Code does not have any problems in sorting, because the keyword in the above example is int type, and it supports less than number calculation. In some special cases, for example, if a keyword is a struct, sorting may occur because it is not inferior to number calculation, and insert and other functions cannot be used during compilation. A method is provided to solve the Sorting Problem-less than the number overload.
# Pragma warning (Disable: 4786)
# Include <map>
# Include <string>
# Include <iostream>
Using namespace STD;
Typedef struct tagstudentinfo
{
Int NID;
String strname;
} Studentinfo, * pstudentinfo; // Student Information
Int main ()
{
// Map scores with student information
Map <studentinfo, int> mapstudent;
Studentinfo;
Studentinfo. nid = 2;
Studentinfo. strname = "one ";
Mapstudent. insert (Map <studentinfo, int >:: value_type (studentinfo, 90 ));
Studentinfo. nid = 1;
Studentinfo. strname = "two ";
Mapstudent. insert (Map <studentinfo, int >:: value_type (studentinfo, 80 ));
}
The above program cannot be compiled, and it must be reloaded with a smaller number.
Typedef struct tagstudentinfo
{
Int NID;
String strname;
Bool operator <(tagstudentinfo const & _ A) const
{// This function specifies the sorting policy, which is sorted by NID. If NID is equal, it is sorted by strname.
If (NID <_ A. NID) return true;
If (nid = _ A. NID) return strname. Compare (_ A. strname) <0;
Return false;
}
} Studentinfo, * pstudentinfo;
2.4 delete a node in Map
Two application scenarios:
First, you can only search for one node from the map at a time and delete it.
This type of deletion is relatively simple. You only need to search for the key value in map and delete the found node.
# Pragma warning (Disable: 4786)
# Include <map>
# Include <string>
# Include <iostream>
Using namespace STD;
Void main ()
{
Map <int, string> mapstudent;
Mapstudent. insert (Map <int, string >:value_type (1, "one "));
Mapstudent. insert (Map <int, string >:value_type (2, "two "));
Mapstudent. insert (Map <int, string >:value_type (3, "three "));
Map <int, string >:: iterator ITER;
Iter = mapstudent. Find (1 );
Mapstudent. Erase (ITER );
For (iter = mapstudent. Begin (); iter! = Mapstudent. End (); ITER ++)
{
Cout <ITER-> first <"" <ITER-> second <Endl;
}
}
Type 2: traverse and check all nodes from the map to delete the nodes that meet the conditions.
Application Scenario Description: The system checks spam sessions on a regular basis (the sessions are placed in the map table). Based on the current system time minus the last activity time of the session, the interval between the last and no activity of the session is obtained, if the interval exceeds the predefined value (the session is considered as a spam session and can be forcibly deleted), delete the session and delete the node from the map.
There are two methods:
(1) traverse the map to find all the nodes that meet the conditions, put the key of each corresponding node into a vector, and then retrieve the key value from the vector in sequence, delete a single node.
This method is very primitive and inefficient. The reason for this implementation is that developers do not know much about map usage. This method not only increases the system overhead of the intermediate processing process (creates a cache space), but also adds N (number of nodes to be deleted) queries, this inefficiency is intolerable for frequent operations.
(2) in the process of map traversal, delete the nodes that meet the conditions (this is guaranteed by the data structure characteristics of the map itself ). In the traversal process, the most important thing is how to ensure that the deleted node points the pointer to the next node before the deletion (which is exactly what we want to do). After deleting the current node, the data structure in map can ensure that the pointers of subsequent iterators are valid, and the subsequent nodes are not traversed (this feature is guaranteed by the operations on the red/black tree at the bottom layer of map ). Therefore, you need to direct the iterator to the next node and then delete the currently qualified node.
# Pragma warning (Disable: 4786)
# Include <map>
# Include <string>
# Include <iostream>
Using namespace STD;
Void main ()
{
Map <int, string> mapstudent;
Mapstudent. insert (Map <int, string >:value_type (1, "one "));
Mapstudent. insert (Map <int, string >:value_type (2, "two "));
Mapstudent. insert (Map <int, string >:value_type (3, "three "));
Map <int, string >:: iterator ITER;
String AA = "three ";
Iter = mapstudent. Begin ();
For (; iter! = Mapstudent. End ();)
{
If (ITER-> second)> = aa)
{
// If the deletion conditions are met, delete the current node and point to the following Node
Mapstudent. Erase (ITER ++ );
}
Else
{
// If the conditions are not met, point to the following Node
ITER ++;
}
}
For (iter = mapstudent. Begin (); iter! = Mapstudent. End (); ITER ++)
{
Cout <ITER-> first <"" <ITER-> second <Endl;
}
}
This deletion method is also recommended in the STL source code book. Compare the execution sequence mapstudent. Erase (ITER ++) and mapstudent. Erase (ITER); ITER ++. Perform a simple test to check the execution sequence of the Assembly execution:
Void func (int)
{}
Int main (INT, char **)
{
Int IPOs = 0;
Func (IPOs ++ );
}
Function call func (IPOs ++) execution sequence: Put IPOs into the register EDX (cache up), random IPOs plus operation Inc dword ptr [ebp-0x04]. That is to say, the execution period of IPOs ++ in the function call is completed before the function body func is executed, and the parameters in the function body use copies before the IPOs is added. Analyze mapstudent again. erase (ITER ++) statement. When deleting ITER in the map, cache the ITER and execute ITER ++ to direct it to the next node, then go to the erase function body to perform the delete operation. The ITER used during the delete operation is the cached ITER (that is, the current ITER (the ITER after the add operation) point to the previous node ).
According to the above analysis, we can see that mapstudent. Erase (ITER ++) and MAP student. Erase (ITER); ITER ++; the execution sequence is different. The former performs the add operation before erase execution and before ITER is deleted (invalid). The latter performs the add operation only after erase execution, at this time, the ITER has been deleted (the current iterator has expired). Adding an expired iterator is unpredictable, this writing method will inevitably lead to the failure of the map operation and cause process exceptions.
3 conclusion
Making full use of the powerful functions of map can greatly reduce the workload of programmers. Many lines of code written using traditional methods are often implemented by calling one or two algorithm templates. The map technology allows programmers to write concise and efficient code, making programming easier and more effective.
References
[1] niclai M. josutis. c ++ Library [M]. Wuhan: Huazhong University of Science and Technology Press, 2006.
[2] Scott Meyers. Valid tive STL Chinese version-50 experiences on using STL [M]. Beijing: Tsinghua University Press, 2006.
[3] Hou Jie. STL source code analysis [M]. Wuhan: Huazhong University of Science and Technology Press, 2002.
[4] Wang Changjing, Xue Jinyun. From C ++ to STL [J]. Journal of Jiangxi Normal University, 2004 (8): 231-234.

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.