Use of C + + Map

Source: Internet
Author: User

STD 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 once in the map, and the second may be called the value of that keyword), and because of this feature, it's possible that when we're dealing with one-to-one data, Provides fast channel programming. Here is the STD map internal Data organization, STD map built a red black tree (a non-strict balance of binary tree), the tree has the function of automatic sorting data, so in the STD map all the data are ordered, 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;

1. Map constructor

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:

The first type: Insert function inserted pair data, the following example (although the following code is readily written, should be able to compile under the VC and GCC through, you can run under what effect, under VC Please add this statement, shield 4786 warning #pragma warning ( disable:4786))

#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;    for (iter = Mapstudent.begin (); ITER! = Mapstudent.end (); iter++)    {        cout<<iter->first<< "" < <iter->second<<end;}    }


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<<end;}    }



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-&  gt;second<<end; }}


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<<end;}    }



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<<end;}    }



3. Size of 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 three ways to traverse a map.

The first is to apply the forward iterator, which is everywhere in the above example program, skip the table

The second kind: Apply the inverse iterator, the following example shows, to realize the effect, please run the program from a

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<<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 the location of the data can not be located, due to map characteristics, one-to-one mapping relationship, it is determined that the count function of the return value of only two, either 0, or 1, the occurrence of the situation, of course, returned 1

The second type: 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

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

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.

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"));    If you want to demonstrate the output effect, please select one of the following, you see the effect will be better    //If you want to delete 1, with an iterator to remove    map<int, String>::iterator iter;    iter = Mapstudent.find (1);    Mapstudent.erase (ITER);    If you want to delete 1, delete the    int n = mapstudent.erase (1) with the keyword, or//If you delete it will return 1, otherwise return 0    //With an iterator, a piece of delete    //code to empty    the entire map Mapstudent.earse (Mapstudent.begin (), Mapstudent.end ());    Delete To be noted, is also the characteristics of the STL, the deletion interval is a front closed after the set    //from a plus traversal code, print out it}


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

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<<it    er->first.strname<<endl<<iter->second<<endl;    }}//above program is unable to compile through, as long as the overloaded less than the number, OK, as follows: typedef struct tagstudentinfo{int NID;    String StrName;  BOOL operator < (tagstudentinfo const& _a) const {//This function specifies the sort policy, sort by nid, if Nid is equal, sort by strname if (nid        < _a.nid) return true; if (NID = = _a.nid) return StrnaMe.compare (_a.strname) < 0;    return false; }}studentinfo, *pstudentinfo;    Student Information//second: The application of imitation functions, this time there is no direct less than the number of overloads, program description typedef struct tagstudentinfo{int NID; String StrName;} Studentinfo, *pstudentinfo; Student Information class sort{Public:bool operator () (Studentinfo const &_a, studentinfo const &_b) const {i        F (_a.nid < _b.nid) return true;        if (_a.nid = = _b.nid) return _a.strname.compare (_b.strname) < 0;    return false;    }};int Main () {//With Student information map score 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.

Use of C + + Map

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.