C + + Map Usage Summary

Source: Internet
Author: User

0. Backgroud

This article originated from the blogger (Sunshinewave), to go to their own blog after easy to view

Map is an associative container for STL that provides a one-to-one (where the first can be called a keyword, where each keyword appears only once in the map, and the second may be called the value of the keyword), and because of this feature, it is possible that when we process a one-to-one data, Provides fast channel programming. Here the map of the internal data organization, map built a red black tree (a non-strict balance of binary tree), the tree has automatic sorting of data functions, so in the map all the data is orderly, behind we will see the orderly benefits.

Here's an example of what a one-to-two data map is. For example, in a class, each student's number and his name there is a one by one mapping relationship, this model can be easily described with a map, it is clear that the study number is described in int, the name is described by a string (this article does not use char * to describe the string, but the STL is described by a string), The map description code is given below:

map<int, string> mapStudent;  
Constructors for 1.map

Map provides a total of 6 constructors, this block involves memory allocator these things, skip the table, below we will be exposed to some map construction methods, here is to say, we usually use the following method to construct a map:

map<int, string> mapStudent;  
2. Insertion of data

After constructing the map container, we can insert data into it. Here are three ways to insert data:

First: Inserting the pair data with the Insert function

The following examples (although the following code is handy to write, should be able to compile under the VC and GCC through, you can run under what effect, under the VC please add this statement, shielding 4786 warning #pragma warning (disable:4786))

#include <map>  #include <string>  #include <iostream>  using namespace std;  int main()  {         map<int, string> mapStudent;//pair<int,string>p;p=make_pair(v1,v2);<span style="color: rgb(255, 0, 0); background-color: rgb(240, 248, 255); font-family: Arial; font-size: 13px; "> </span>         mapStudent.insert(pair<int, string>(1, "student_one"));         mapStudent.insert(pair<int, string>(2, "student_two"));         mapStudent.insert(pair<int, string>(3, "student_three"));         map<int, string>::iterator  iter;         for(iter = mapStudent.begin(); iter != mapStudent.end(); iter++)         {            cout<<iter->first<<"  "<<iter->second<<endl;         }  }  

Make_pair ()//return type is the corresponding pair type

You can generate a pair object without having to write out a category

Cases:

make_pair(1,‘@‘)  

Without straining to write

pair<int ,char>(1,‘@‘)  
The second type: Insert the Value_type data with the Insert function, the following examples illustrate
#include <map>  #include <string>  #include <iostream>  using namespace std;  int main()  {         map<int, string> mapStudent;         mapStudent.insert(map<int, string>::value_type (1, "student_one"));         mapStudent.insert(map<int, string>::value_type (2, "student_two"));         mapStudent.insert(map<int, string>::value_type (3, "student_three"));         map<int, string>::iterator  iter;         for(iter = mapStudent.begin(); iter != mapStudent.end(); iter++)         {             cout<<iter->first<<" "<<iter->second<<endl;         }  }  
The third type: Insert the data in an array way, as illustrated below
#include <map>  #include <string>  #include <iostream>  using namespace std;  int main()  {         map<int, string> mapStudent;         mapStudent[1] =  "student_one";         mapStudent[2] =  "student_two";         mapStudent[3] =  "student_three";         map<int, string>::iterator  iter;         for(iter = mapStudent.begin(); iter != mapStudent.end(); iter++)         {            cout<<iter->first<<"   "<<iter->second<<endl;         }  }  

The above three kinds of usage, although can achieve data insertion, but they are different, of course, the first and the second in the effect is done, insert the data with the Insert function, the insertion of the data involves the concept of the uniqueness of the collection, that is, when the map has this keyword, Insert operation is not the insertion of data, but the array is different, it can overwrite the previous value corresponding to the keyword, using the program description

mapStudent.insert(map<int, string>::value_type (1, "student_one"));  mapStudent.insert(map<int, string>::value_type (1, "student_two"));  

Above these two statements executed, the map in 1 the value of this keyword is "Student_one", the second statement does not take effect, then this relates to how we know the INSERT statement is inserted into the success of the problem, you can use the pair to get the insertion success, the program is as follows

Pair<map<int, string>::iterator, bool> Insert_Pair;  Insert_Pair = mapStudent.insert(map<int, string>::value_type (1, "student_one"));  

We know whether the insert succeeds by the second variable of the Pair, and its first variable returns a map iterator that Insert_pair.second should be true if the insert succeeds, otherwise false.

The completion code is given below to demonstrate the success of the insert.

#include <map> #include <string> #include <iostream> using namespace std;         int main () {map<int, string> mapstudent;         Pair<map<int, String>::iterator, bool> Insert_pair;         Insert_pair = Mapstudent.insert (Pair<int, string> (1, "Student_one"));         If (Insert_pair.second = = true) {cout<< "Insert successfully" <<endl;         } Else {cout<< "Insert Failure" <<endl;         } Insert_pair = Mapstudent.insert (Pair<int, string> (1, "student_two"));         If (Insert_pair.second = = true) {cout<< "Insert successfully" <<endl;         } Else {cout<< "Insert Failure" <<endl;         } map<int, String>::iterator iter; for (iter = Mapstudent.begin (); ITER! = Mapstudent.end (); iter++) {cout<<iter->first<< "" <<iter->second<<endl;   }  }

You can use the following procedure to see the effect of inserting an array on the data overlay

#include <map>  #include <string>  #include <iostream>  using namespace std;  int main()  {         map<int, string> mapStudent;         mapStudent[1] =  "student_one";         mapStudent[1] =  "student_two";         mapStudent[2] =  "student_three";         map<int, string>::iterator  iter;         for(iter = mapStudent.begin(); iter != mapStudent.end(); iter++)         {            cout<<iter->first<<"   "<<iter->second<<endl;         }  }  
Size of 3.map

When we insert data into a map, how do we know how much data is currently inserted, and we can use the size function as follows:

int nSize = mapStudent.size();  
4. Traversal of data

There are also three ways to make a map

The first kind: the application of Forward iterators, the above examples of the program is everywhere, skip the second: The application of reversed-phase iterator, the following examples illustrate, to realize the effect, please run the program from the start
#include <map>  #include <string>  #include <iostream>  using namespace std;  int main()  {         map<int, string> mapStudent;         mapStudent.insert(pair<int, string>(1, "student_one"));         mapStudent.insert(pair<int, string>(2, "student_two"));         mapStudent.insert(pair<int, string>(3, "student_three"));         map<int, string>::reverse_iterator  iter;         for(iter = mapStudent.rbegin(); iter != mapStudent.rend(); iter++)         {            cout<<iter->first<<"   "<<iter->second<<endl;         }  }  
The third type: Using the array method, the program is described as follows
#include <map>  #include <string>  #include <iostream>  using namespace std;  int main()  {         map<int, string> mapStudent;         mapStudent.insert(pair<int, string>(1, "student_one"));         mapStudent.insert(pair<int, string>(2, "student_two"));         mapStudent.insert(pair<int, string>(3, "student_three"));         int nSize = mapStudent.size()  //此处有误,应该是 for(int nIndex = 1; nIndex <= nSize; nIndex++)   //by rainfish         for(int nIndex = 0; nIndex < nSize; nIndex++)         {             cout<<mapStudent[nIndex]<<end;         }  
5. Data lookup (including determining if the keyword appears in the map)

Here we will realize that map ensures an orderly benefit when data is inserted.
To determine whether a data (keyword) appears in the map of the method is more, where the title is a data lookup, here will be interspersed with a large number of map basic usage.

Here are three ways to find the data:

The first: Use the Count function to determine whether the keyword appears, the disadvantage is that it cannot locate the location of the data, due to the map's characteristics, one-to-one mapping relationship, it determines the value of the Count function is only two, either 0, or 1, the occurrence of the situation, Of course, it returns 1. The second kind: Use the Find function to locate the location of the data, it returns an iterator, when the data appears, it returns the iterator where the data is located, if there is no data to find in the map, it returns an iterator equal to the iterator returned by the End Function, the program description
#include <map>  #include <string>  #include <iostream>  using namespace std;  int main()  {         map<int, string> mapStudent;         mapStudent.insert(pair<int, string>(1, "student_one"));         mapStudent.insert(pair<int, string>(2, "student_two"));         mapStudent.insert(pair<int, string>(3, "student_three"));         map<int, string>::iterator iter;         iter = mapStudent.find(1);         if(iter != mapStudent.end())        {             cout<<"Find, the value is "<<iter->second<<endl;         }         Else         {             cout<<"Do not Find"<<endl;         }  }  
The third: This method is used to determine whether the data appears, it seems stupid point, but I am going to explain here

Lower_bound function usage, this function is used to return the lower bound of the keyword to find (is an iterator)

Upper_bound function usage, which is used to return the upper bound of the keyword to find (is an iterator)

For example, if 1,2,3,4 is already inserted in the map, if Lower_bound (2) returns 2, and Upper-bound (2), the return is 3.

The Equal_range function returns an iterator in which the first variable inside the Pair,pair is the Lower_bound return, and the second iterator inside the pair is the iterator that Upper_bound returns, and if the two iterators are equal, This keyword does not appear in the map, the program description

#include <map> #include <string> #include <iostream> using namespace std;         int main () {map<int, string> mapstudent;         MAPSTUDENT[1] = "Student_one";         MAPSTUDENT[3] = "Student_three";         MAPSTUDENT[5] = "student_five";         Map<int, String>::iterator iter;        iter = Mapstudent.lower_bound (2);         {//Returns an iterator to the Nether 3 cout<<iter->second<<endl;         iter = Mapstudent.lower_bound (3);         {//Returns an iterator to the Nether 3 cout<<iter->second<<endl;         iter = Mapstudent.upper_bound (2);         {//Returns an iterator with an upper bound of 3 cout<<iter->second<<endl;        iter = Mapstudent.upper_bound (3);  {//Returns an iterator with an upper bound of 5 cout<<iter->second<<endl;        } pair<map<int, String>::iterator, Map<int, string>::iterator> Mappair;        Mappair = Mapstudent.equal_range (2); if (MAPpair.first = = Mappair.second) {cout<< "Do not Find" <<endl;          } Else {cout<< "Find" <<endl;         } Mappair = Mapstudent.equal_range (3);          if (Mappair.first = = Mappair.second) {cout<< "Do not Find" <<endl;         } Else {cout<< "Find" <<endl;   }  }
6. Emptying of data and empty sentences

Emptying the data in the map can use the clear () function to determine if there is data in the map with the empty () function, which returns true to indicate that it is an empty map

7. Deletion of data

Here we use the Erase function, which has three overloaded functions, which are explained in detail in the examples below.

#include <map>  #include <string>  #include <iostream>  using namespace std;  int main()  {         map<int, string> mapStudent;         mapStudent.insert(pair<int, string>(1, "student_one"));         mapStudent.insert(pair<int, string>(2, "student_two"));         mapStudent.insert(pair<int, string>(3, "student_three"));         //如果你要演示输出效果,请选择以下的一种,你看到的效果会比较好         //如果要删除1,用迭代器删除         map<int, string>::iterator iter;         iter = mapStudent.find(1);         mapStudent.erase(iter);         //如果要删除1,用关键字删除         int n = mapStudent.erase(1);//如果删除了会返回1,否则返回0         //用迭代器,成片的删除         //一下代码把整个map清空         mapStudent.earse(mapStudent.begin(), mapStudent.end());         //成片删除要注意的是,也是STL的特性,删除区间是一个前闭后开的集合       //自个加上遍历代码,打印输出吧  }  
8. Some other function usages

There are swap,key_comp,value_comp,get_allocator, such as functions, feel that these functions in the programming is not a lot, skip the table, interested can be self-study

9. Sorting

Here is a bit more advanced usage, sorting problems, STL default is to use less than the number to sort, the above code in the sort is no problem, because the above keyword is an int, which itself supports less than the number of operations, in some special cases, such as the keyword is a struct, Problems related to sorting, because it has no less than operation, insert and other functions at the time of compilation, the following two ways to solve the problem

The first type: less than the number of overloads, program examples
#include <map> #include <string> uing namespace std;         Typedef struct Tagstudentinfo {int nID;  String StrName;  }studentinfo, *pstudentinfo;         Student Information int main () {int nSize;         Mapping score Map<studentinfo with student information, int>mapstudent;         Map<studentinfo, Int>::iterator iter;         Studentinfo Studentinfo;         Studentinfo.nid = 1;         Studentinfo.strname = "Student_one" Mapstudent.insert (Pair<studentinfo, int> (Studentinfo, 90));         Studentinfo.nid = 2;         Studentinfo.strname = "Student_two";         Mapstudent.insert (Pair<studentinfo, int> (Studentinfo, 80)); For (Iter=mapstudent.begin (); Iter!=mapstudent.end (); iter++) cout<<iter->first.nid<<endl<<  iter->first.strname<<endl<<iter->second<<endl;         The above program can not be compiled through, as long as the overloaded less than the number, OK, as follows: [CPP] View plain copytypedef struct Tagstudentinfo {int nID; String StrnaMe                Bool operator < (tagstudentinfo const& _a) const {//This function specifies a sort policy, sort by nid, sort by strname if Nid is equal                If (NID < _a.nid) return true;                If (NID = = _a.nid) return Strname.compare (_a.strname) < 0;         Return false;  }}studentinfo, *pstudentinfo;   Student Information
The second kind: the application of the pseudo function, this time there is no direct less than the number of overloaded, program description
#include <map>  #include <string>  using namespace std;  Typedef struct tagStudentInfo  {         int      nID;         String   strName;  }StudentInfo, *PStudentInfo;  //学生信息  class sort  {         Public:         Bool operator() (StudentInfo const &_A, StudentInfo const &_B) const         {                If(_A.nID < _B.nID) return true;                If(_A.nID == _B.nID) return _A.strName.compare(_B.strName) < 0;                Return false;         }  };  int main()  {         //用学生信息映射分数         map<StudentInfo, int, sort>mapStudent;         StudentInfo studentInfo;         studentInfo.nID = 1;         studentInfo.strName = "student_one";         mapStudent.insert(pair<StudentInfo, int>(studentInfo, 90));         studentInfo.nID = 2;         studentInfo.strName = "student_two";         mapStudent.insert(pair<StudentInfo, int>(studentInfo, 80));  }  
10. In addition

Because the STL is a unified whole, many uses of map are combined with other things in the STL, for example, in the sort, here the default is less than the number, that is, LESS<>, if you want to sort from large to small, there are a lot of things involved, here can not be explained.

It is also stated that the map because of its internal order, by the red and black tree guarantee, so many function execution time complexity is log2n, if the function can be implemented with the map function, and the STL algorithm can also complete the function, it is recommended to use the map with the function, high efficiency.

Below, the map in the spatial characteristics, otherwise, you may be used to the performance of the more depressed, because map of each data corresponding to a node on the red and black tree, this node in not saving your data, is occupied 16 bytes, a parent node pointer, left and right child pointer, There is also an enumeration value (labeled Red-black, equivalent to the balance factor in the balanced binary tree), and I think you should know that these places are very memory-consuming.

C + + Map Usage Summary

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.