Introduction to C + +--map of standard Template Library

Source: Internet
Author: User

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 is the map of the internal data of the organization, map built a red black tree (a non-strict balance of the binary tree), the tree has the function of automatic sorting of data, so in the map all the data is orderly, behind we will see the orderly benefits.


So what is a one-to data map? 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.


Before using map, you must include the corresponding header file, map belongs to the STD named domain, so you need to pass the name qualification:

#include <map>

Using Std::map; using namespace Std;


1) Map constructorMap provides a total of 6 constructors, this block involves memory allocator these things, skip over, below we will be exposed to some map construction methods, we usually use the following methods 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:

A) Insert the pair data with the Insert function:

#include <iostream> #include <map>//map#include <string>//string#include <utility>// Pairusing std::endl;using std::cin;using std::cout;using std::map;using std::string;using std::p air;//using namespace std;//or directly include all//insert functions into pair data int main (int argc, char *argv[]) {map<int, string> mapstudent;// Insert function inserts the pair data Mapstudent.insert (Pair<int, string> (1, "Student_one")), Mapstudent.insert (Pair<int, String> (2, "student_two")); Mapstudent.insert (Pair<int, string> (3, "Student_three"));//Iterate through the map's contents map <int, String>::iterator iter;for (iter = Mapstudent.begin (); ITER! = Mapstudent.end (); iter++) {    cout<< iter->first<< "" <<iter->second<<endl;} return 0;}

The results of the operation are as follows:



b) Insert the Value_type data using the Insert function:

#include <iostream> #include <map>//map pair#include <string>//string#include <utility>// Pairusing std::endl;using std::cin;using std::cout;using std::map;using std::string;using std::p air;//using namespace std;//or directly include all//insert functions into Value_type data int main (int argc, char *argv[]) {map<int, string> mapstudent;// Insert the Value_type data Mapstudent.insert (Map<int, String>::value_type (1, "Student_one") with the Insert function; Mapstudent.insert (Map<int, String>::value_type (2, "student_two")); Mapstudent.insert (Map<int, String>::value_type (3, " Student_three ");//Iterate through the contents of the map Map<int, String>::iterator iter;for (iter = Mapstudent.begin (); ITER! = Mapstudent.end (); iter++) {    cout<<iter->first<< "" <<ITER->SECOND<<ENDL;} return 0;}

c) Insert the data in an array mode:

#include <iostream> #include <map>//map pair#include <string>//stringusing std::endl;using std::cin ; using std::cout;using std::map;using std::string;using std::p air;//using namespace std;//or directly include all//insert data in array mode int Main (int argc, char *argv[]) {map<int, string> mapstudent;//insert data in array mode mapstudent[0] = "Student_one"; mapstudent[2] = "Student_two"; mapstudent[3] = "student_three";//Iterate through the contents of the map Map<int, String>::iterator iter;for (iter = Mapstudent.begin (); Iter! = Mapstudent.end (); iter++) {    cout<<iter->first<< "" <<ITER->SECOND<<ENDL;} return 0;}

The results of the operation are as follows:


The above three usages, although all can realize the data inserting, but they are different. The first and second are done in effect, insert the data with the Insert function, the concept of the uniqueness of the collection is involved in the insertion of the data, that is, when a keyword is already present in the map, the insert operation is not able to insert the data successfully, but it can be used in the array mode. It can overwrite the value corresponding to the previous keyword.


How do we know if the INSERT statement was successful? We can use pair to get the insertion success:

pair< Map<int, string>::iterator, bool > Insert_pair;insert_pair = Mapstudent.insert (Map<int, string >::value_type (1, "Student_one"));


We use the second variable of the pair to determine whether the insertion succeeds, its first variable returns a map iterator, or False if the insertion succeeds Insert_pair.second.


The complete test code is as follows:

#include <iostream> #include <map>//map pair#include <string>//stringusing std::endl;using std::cin ; using std::cout;using std::map;using std::string;using std::p air;//using namespace std;//or directly put all included//test insert succeeded int main (int argc, char *argv[]) {map<int, string> mapstudent;pair<map<int, string>::iterator, bool> insert_pair;//inserting data insert_pair = Mapstudent.insert (Pair<int, string> (1, "Student_one")); if (Insert_pair.second = = true)//Insert Success {cout << " Insert successfully "<< Endl;} Else{cout << "Insert Failure" << Endl;} Insert Data Insert_pair = Mapstudent.insert (Pair<int, string> (1, "Student_two")), if (Insert_pair.second = = true)// Insert Success {cout << "insert successfully" << Endl;} Else{cout << "Insert Failure" << Endl;} cout << "\ n------------------------\ n";//Iterate through the contents of the map Map<int, String>::iterator iter;for (iter = Mapstudent.begin (); Iter! = Mapstudent.end (); iter++) {cout<<iter->first<< ""<<iter->second<<endl;} return 0;}

The results of the operation are as follows:



The following example assigns a value to a test array and overwrites the problem with the data:

#include <iostream> #include <map>//map pair#include <string>//stringusing std::endl;using std::cin , using std::cout;using std::map;using std::string;using std::p air;//using namespace std;//or directly assign all include//test array, Data coverage issues int main (int argc, char *argv[]) {map<int, string> mapstudent;mapstudent[1] = "Student_one"; mapstudent[1] = " Student_two ";//This is 1mapstudent[2] =" Student_three "; cout <<" \ n------------------------\ n ";// Traverse the contents of the map via an iterator map<int, String>::iterator iter;for (iter = Mapstudent.begin (); ITER! = Mapstudent.end (); iter++) {    cout<<iter->first<< "" <<ITER->SECOND<<ENDL;} return 0;}

The results of the operation are as follows:



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

A) pass forward iterators, which are used in the above example procedure.


b) by inverting the iterator:

#include <iostream> #include <map>//map pair#include <string>//stringusing std::endl;using std::cin ; using std::cout;using std::map;using std::string;using std::p air;//using namespace std;//or directly include all// Use an inverse iterator to traverse the map contents int main (int argc, char *argv[]) {map<int, string> mapstudent;// Insert function inserts the pair data Mapstudent.insert (Pair<int, string> (1, "Student_one")), Mapstudent.insert (Pair<int, String> (2, "Student_two")), Mapstudent.insert (Pair<int, string> (3, "Student_three")),//cout << "\ n------------------------\ r ";//Use an inverting iterator to traverse the map content map<int, String>::reverse_iterator iter;for (iter = Mapstudent.rbegin (); Iter! = Mapstudent.rend (); iter++) {    cout<<iter->first<< "" <<ITER->SECOND<<ENDL;} return 0;}


The results of the operation are as follows:



c) by means of an array:

#include <iostream> #include <map>//map pair#include <string>//stringusing std::endl;using std::cin ; using std::cout;using std::map;using std::string;using std::p air;//using namespace std;//or directly include all// Use an array to traverse the map contents int main (int argc, char *argv[]) {map<int, string> mapstudent;//Insert the pair data with the Insert function Mapstudent.insert (Pair<int, string> (1, "Student_one")); Mapstudent.insert (Pair<int, string> (2, "student_two")); Mapstudent.insert (Pair<int, string> (3, "Student_three")),//cout << "\ n------------------------\ n";// Use an array to traverse the map contents int n = mapstudent.size (); for (int i = 1; I <= n; i++)//starting from 1 {    cout<< i << "" << map Student[i]<<endl;} return 0;}

5) Finding the data

You can use the Find function to locate where the data appears, and it returns an iterator that, when the data appears, returns an iterator where the data is located, and if there is no data to find in the map, it returns an iterator equal to the iterator returned by the End function. The sample code is as follows:

#include <iostream> #include <map>//map pair#include <string>//stringusing std::endl;using std::cin ; using std::cout;using std::map;using std::string;using std::p air;//using namespace std;//or directly include all// Locate data with the Find function position int main (int argc, char *argv[]) {map<int, string> mapstudent;// Insert function inserts the pair data 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); Find the content of 1 if (iter! = Mapstudent.end ())//Find {    cout << "Find, the value is:" << iter->second << E NDL;} else{    cout << "Do not Find" << Endl;} return 0;}

The results of the operation are as follows:



6) The data is emptied and emptyemptying 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 an empty map.


7) Deletion of dataHere we use the Erase function, which has three overloaded functions, which are described in detail in the following example:

#include <iostream> #include <map>//map pair#include <string>//stringusing std::endl;using std::cin ; using std::cout;using std::map;using std::string;using std::p air;//using namespace std;//or directly all contain//data deleted int main ( int argc, char *argv[]) {map<int, string> mapstudent;//inserts the pair data Mapstudent.insert with the Insert function (Pair<int, string > (0, "Student_zero")); Mapstudent.insert (Pair<int, string> (1, "Student_one")); Mapstudent.insert (pair< int, string> (2, "student_two")); Mapstudent.insert (Pair<int, string> (3, "Student_three")); Mapstudent.insert (Pair<int, string> (4, "Student_four"));//If you want to remove 1, remove Map<int with iterators, String>::iterator ITER ; iter = Mapstudent.find (1); Find 1mapstudent.erase (ITER) First, cout << "\nafter erase 1:\n";//Iterate through the contents of the map for (iter = Mapstudent.begin (); ITER! = Mapstudent.end (); iter++) {cout<<iter->first<< "" &LT;&LT;ITER-&GT;SECOND&LT;&LT;ENDL;} If you want to delete 2, the available keywords are deleted int n = mapstudent.erase (2);//If Delete succeeds returns 1, return 0cout << "n =" << n << endl;cout << "\nafter erase 2:\n";//Iterate through the contents of the map for (iter = Mapstudent.begin (); Iter! = Mapstudent.end (); iter++) {cout<<iter->first<< "" &LT;&LT;ITER-&GT;SECOND&LT;&LT;ENDL;} With an iterator, a piece of delete//piece Delete to note is also the STL feature, the deletion interval is a front closed after the set Mapstudent.erase (Mapstudent.begin (), Mapstudent.end ()); cout < < "\nafter erase all:\n";//Iterate through the contents of the map for (iter = Mapstudent.begin (); ITER! = Mapstudent.end (); iter++) {COUT&LT;&L t;iter->first<< "" <<iter->second<<endl;} return 0;}

The results of the operation are as follows:



8) Sort

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 not any 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, There is a problem with sorting, because it has no less than operation, the insert and other functions at compile time, the test code is as follows:

#include <iostream> #include <map>//map pair#include <string>//stringusing std::endl;using std::cin ; using std::cout;using std::map;using std::string;using std::p air;//using namespace std;//or directly include all typedef structs Tagstudentinfo{int nid;string StrName;} Studentinfo, *pstudentinfo; Student information//Data deletion int main (int argc, char *argv[]) {/////With Student information mapping score map<studentinfo, int> mapstudent; Studentinfo Studentinfo;studentinfo.nid = 1;studentinfo.strname = "Student_one"; Mapstudent.insert (pair< Studentinfo, int> (Studentinfo, n)) Studentinfo.nid = 2;studentinfo.strname = "Student_two"; MapStudent.insert ( Pair<studentinfo, Int> (Studentinfo, 80)); Map<studentinfo, Int>::iterator iter;for (iter = Mapstudent.begin (); ITER! = Mapstudent.end (); iter++) {cout< <iter->first.nID<< "<<iter->first.strName<<" "<<ITER->SECOND<<ENDL; return 0;}

The above program cannot be compiled through .

The workaround is: overload less than sign . Examples are as follows:

#include <iostream> #include <map>//map pair#include <string>//stringusing std::endl;using std::cin ; using std::cout;using std::map;using std::string;using std::p air;//using namespace std;//or directly include all typedef structs Tagstudentinfo{int nid;string strname;bool operator< (tagstudentinfo const &temp) const{//This function specifies a sort policy, sorted by NID, If Nid is equal, press StrName to sort if (Nid < Temp.nid) return true;if (nid = = Temp.nid) return Strname.compare (Temp.strname); return false;}} Studentinfo, *pstudentinfo; Student information//Data deletion int main (int argc, char *argv[]) {/////With Student information mapping score map<studentinfo, int> mapstudent; Studentinfo Studentinfo;studentinfo.nid = 1;studentinfo.strname = "Student_one"; Mapstudent.insert (pair< Studentinfo, int> (Studentinfo, n)) Studentinfo.nid = 2;studentinfo.strname = "Student_two"; MapStudent.insert ( Pair<studentinfo, Int> (Studentinfo, 80)); Map<studentinfo, Int>::iterator iter;for (iter = Mapstudent.begin (); ITER! = Mapstudent.end (); iter++) {cout< <iter->first.nid<< "<<iter->first.strName<<" "&LT;&LT;ITER-&GT;SECOND&LT;&LT;ENDL;} return 0;}

run the result diagram as follows:



This article transferred from: Http://www.kuqin.com/cpluspluslib


Copyright NOTICE: This blog post, mostly I compiled, or in the network collection, reproduced please indicate the source!!

Introduction to C + +--map of standard Template Library

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.