An explanation of the use of associative container map in STL

Source: Internet
Author: User
Tags bool

MapIsSTL, which provides one-to-one (where the first one can be called a keyword, each keyword
Only inMapA second, possibly called the value of the keyword), due to this feature,
It is entirely possible to provide fast-track programming when we process one-to-one data. Here's the map interior number.
According to the organization, map built a red-black tree (a non-strictly balanced binary tree), the tree has a logarithmic
According to the automatic sorting function, so all the data inside the map is orderly, we will see the orderly benefits behind.

Here's an example of what a one-to-two data map is. For example, in a class, each student's school number and his name
There is a one by one mapping relationship, this model can be easily described with map, it is clear that the study number withintDescription, name with
String description (This article does notchar *To describe the string, but instead uses theSTLInstringTo describe), the following gives
OutMapDescription Code:Map<int, string> mapstudent;
Constructors for 1.map
MapA total of 6 constructors are provided, this block relates to the memory allocator of these things, slightly over the table, below which we will pick up
Touch a fewMapThe construction method, here is to say, we usually use the following methods to construct aMap
Map<int, string> mapstudent;
2. Insertion of data
In the constructionMapContainer, we can insert data into it. Here are three ways to insert data:
The first type: WithInsertfunction insertionpairData, as illustrated below (although the following code is readily written, it should be
Under the VC and GCC compiled through, everyone can run under what effect, inVCPlease add this statement to block the 4786 police
Sue
#include "stdafx.h"
#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<<endl;
}
GetChar ();
return 0;
}

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


The above three usages, although can achieve the data insertion, but they are different, of course the first and the second kind in the effect
On is done the same, withInsertThe function inserts data, which involves the concept of the uniqueness of the collection on the insertion of the data, that is, when
MapWhen you have this keyword in theInsertThe operation is not able to insert data, but the array is different, it can overwrite the previous
The 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"));

When the above two statements are executed,MapThe value for this keyword in 1 is "Student_one", the second statement does not take effect,
Then this involves how we know if the INSERT statement is inserted successfully, and you can use the pair to get the insertion success.
The procedure is as follows:

Pair<map<int, String>::iterator, bool> Insert_pair;
Insert_pair = Mapstudent.insert (Map<int, String>::value_type (1, "Student_one"));

We passpairThe second variable to know whether the insert succeeds, its first variable returns aMapThe iterator, if
If you insert it successfullyInsert_pair.secondShould betrue, otherwisefalse

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<< "Student_one Insert successfully" <<endl;
}
Else
{
cout<< "Student_one Insert Failure" <<endl;
}
Insert_pair = Mapstudent.insert (Pair<int, string> (1, "student_two"));
if (Insert_pair.second = = True)
{
cout<< "Student_two Insert successfully" <<endl;
}
Else
{
cout<< "Student_two Insert Failure" <<endl;
}
Map<int, String>::iterator iter;
for (iter = Mapstudent.begin (); ITER! = Mapstudent.end (); iter++)
{
cout<<iter->first<< "." <<iter->second<<endl;
}
GetChar ();
return 0;
}


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;
}
GetChar ();
return 0;
}

size of 3.map
On the GoMapInsert the data inside, how do we know how much data is currently inserted, you can use the size function, use the following:
int nSize = Mapstudent.size ();
4. Traversal of data
There are three ways toMapto traverse
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
#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 = 0; NIndex <= nSize; nindex++)
{
cout<<mapstudent[nindex]<<endl;
}
GetChar ();
return 0;
}

5. Data lookup (including determining if the keyword appears in the map)
Here we will experience,MapEnsures an orderly benefit when data is inserted.
To determine whether a data (keyword) appears in the Map method is more, where the title is a data lookup, in this
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 characteristics of the map,
A one-to-one mapping relationship determines that the return value of the Count function is only two, either 0, or 1, in the event that
Of course it's back to 1.
The second: Use the Find function to locate where the data appears, and it returns an iterator that returns the data when the data appears
In the position of the iterator, if there is no data in the map to find, it returns an iterator equal to the iterator returned by the End function, and 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 (2);
if (iter! = Mapstudent.end ())
{
cout<< "Find, the value is" <<iter->second<<endl;
}
Else
{
cout<< "Do not Find" <<endl;
}
GetChar ();
return 0;
}

The third: This method is used to determine whether the data appears, it seems stupid point, but I am going to explain here
Lower_boundfunction usage, which is used to return the lower bound of the keyword to find (is an iterator)
Upper_boundfunction usage, which is used to return the upper bound of the keyword to find (is an iterator)
For example:Maphas been inserted in the 1,2,3,4, ifLower_bound (2)Words, returned to the 2, while
Upper-bound (2), the return is 3.
Equal_rangeThe function returns a Pair,pair inside the first variable isLower_boundReturns an iterator that
pairThe second iterator inside 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);
{
An iterator that returns an upper bound of 3
cout<<iter->second<<endl;
}
iter = Mapstudent.upper_bound (3);
{
An iterator that returns 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 any data in the map can be used with the empty () function, which returns
True indicates 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"));
If you want to demonstrate the output, choose one of the following, and you'll see better results.
If you want to remove 1, use an iterator to remove
Map<int, String>::iterator iter;
iter = Mapstudent.find (1);
Mapstudent.erase (ITER);
If you want to delete 1, delete it with the keyword
int n = mapstudent.erase (1);//returns 1 if deleted, otherwise 0
Use iterators to delete slices
A little bit of code to empty the map.
Mapstudent.earse (Mapstudent.begin (), Mapstudent.end ());
Delete to be aware of, is also the characteristics of the STL, delete interval is a front closed after the set
From a plus traverse code, print out
}

8. Some other function usages
There are functions like swap,key_comp,value_comp,get_allocator, which feel that these functions are used in programming
Not a lot, skip the table, if you are interested, you can study from a

9. Sorting
Here is a bit more advanced usage, sorting problems, STL default is to use less than the number to sort, to
The above code does not have any problem with the sort, because the above keyword is the int type, which itself supports the less than sign
Operations, in some special cases, such as the keyword is a struct, the problem is related to sorting, because it
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>
Using namespace Std;
Typedef struct Tagstudentinfo
{
Int NID;
String StrName;
}studentinfo, *pstudentinfo; Student Information

Int Main ()
{
int nSize;
Mapping scores with student information
Map<studentinfo, 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 is not compiled 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, and 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


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;
      & nbsp String   StrName;
}studentinfo, *pstudentinfo;  //Student Information

Classs 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 ()
{
       //
Mapping scores with student information
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));
}

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.