C ++ STL map Learning

Source: Internet
Author: User

Map <key, Data, compare, alloc>

 

Map is an associated container that stores elements that combine key values and ing values.MapIs a pair
Associative container, which means that its value type isPair <const key, data>And
Unique associative container, that is, no two elements have the same key value.

A map has an important attribute, that is, it fails to insert a new element into the map object without pointing to an existing element iterator. Deleting an element from a map does not invalidate any iterator unless, of course, actually pointing to the iterator of the element being deleted.

 

1. Example

struct ltstr{  bool operator()(const char* s1, const char* s2) const  {    return strcmp(s1, s2) < 0;  }};int main(){  map<const char*, int, ltstr> months;    months["january"] = 31;  months["february"] = 28;  months["march"] = 31;  months["april"] = 30;  months["may"] = 31;  months["june"] = 30;  months["july"] = 31;  months["august"] = 31;  months["september"] = 30;  months["october"] = 31;  months["november"] = 30;  months["december"] = 31;    cout << "june -> " << months["june"] << endl;  map<const char*, int, ltstr>::iterator cur  = months.find("june");  map<const char*, int, ltstr>::iterator prev = cur;  map<const char*, int, ltstr>::iterator next = cur;      ++next;  --prev;  cout << "Previous (in alphabetical order) is " << (*prev).first << endl;  cout << "Next (in alphabetical order) is " << (*next).first << endl;}

 

2. Definition form

template < class Key, class T, class Compare = less<Key>,           class Allocator = allocator<pair<const Key,T> > > class map;

 

3. template parameters have the following meanings:

Key: Type of the key value. Each element in the map object uniquely identifies the element through the key value.
T: Type of the ing value. Each element in map is used to store some data as its ing value.
Compare: comparison class: Type of the Class A key. It has two parameters and returns a bool. Expression of COMP (a, B). Comp is the key value object for this comparison class A and B. True should be returned, if it is placed in an earlier position than B in a strictly weak sorting operation. This can be a class that implements a function call operator or a function pointer (see an example ). For <key> by default, the return request is smaller than the default value of the same operator (
<B ).
The map object uses this expression to determine the position of elements in the container. The following rule lists all elements in the map container at any time.
Allocator: defines the type of the Storage Allocation Model distributor object. By default, a distributor template defines the simplest memory allocation mode, which is independent of values.

 

Map <key, T>: iterator it; (* it ). first; // point to the key value (of type key) (* it ). second; // ing value (of type T) (* It); // The "element value" (of Type pair <const key, T>)

It can also be expressed as follows:

it->first;               // same as (*it).first   (the key value)it->second;              // same as (*it).second  (the mapped value)

 

 

4. member variables and member functions

Member Where defined Description
Key_type Associative container Key type in Map
Data_type Pair associative container Value type associated with key
Value_type Pair associative container Object type,Pair <const key_type, data_type>, Stored in Map
Key_compare Sorted associative container Function object through sequential comparison
Value_compare Sorted associative container Function object that compares two values for ordering.
Pointer Container PointerT.
Reference Container ReferenceT
Const_reference Container Const referenceT
Size_type Container An unsigned integral type.
Difference_type Container A signed integral type.
Iterator Container Iterator used to iterate throughMap. [1]
Const_iterator Container Const iterator used to iterate throughMap.
Reverse_iterator Reversible container Iterator used to iterate backwards throughMap.
[1]
Const_reverse_iterator Reversible container Const iterator used to iterate backwards throughMap.
Iterator begin () Container ReturnsIteratorPointing to the beginning of
Map.
Iterator end () Container ReturnsIteratorPointing to the end ofMap.
Const_iterator begin () const Container ReturnsConst_iteratorPointing to the beginning ofMap.
Const_iterator end () const Container ReturnsConst_iteratorPointing to the end of
Map.
Reverse_iterator rbegin () Reversible container ReturnsReverse_iteratorPointing to the beginning of the reversed map.
Reverse_iterator rend () Reversible container ReturnsReverse_iteratorPointing to the end of the reversed map.
Const_reverse_iterator rbegin () const Reversible container ReturnsConst_reverse_iteratorPointing to the beginning of the reversed map.
Const_reverse_iterator rend () const Reversible container ReturnsConst_reverse_iteratorPointing to the end of the reversed map.
Size_type size () const Container Returns the size ofMap.
Size_type max_size () const Container Returns the largest possible size ofMap.
Bool empty () const Container TrueIfMap'S size is0.
Key_compare key_comp () const Sorted associative container ReturnsKey_compareObject used byMap.
Value_compare value_comp () const Sorted associative container ReturnsValue_compareObject used byMap.
Map () Container Creates an emptyMap.
Map (const key_compare & Comp) Sorted associative container Creates an emptyMap, UsingCompAsKey_compareObject.
template <class InputIterator>map(InputIterator f, InputIterator l)
Unique sorted associative container Creates a map with a copy of a range.
template <class InputIterator>map(InputIterator f, InputIterator l,    const key_compare& comp)
Unique sorted associative container Creates a map with a copy of a range, usingCompAsKey_compareObject.
Map (const map &) Container The copy constructor.
Map & operator = (const map &) Container The assignment operator
Void swap (MAP &) Container Swaps the contents of two maps.
pair<iterator, bool>insert(const value_type& x)
Unique associative container InsertsXIntoMap.
iterator insert(iterator pos,                const value_type& x)
Unique sorted associative container InsertsXIntoMap, UsingPosAs a hint to where it will be inserted.
template <class InputIterator>void insert(InputIterator, InputIterator)[2]
Unique sorted associative container Inserts a range intoMap.
Void erase (iterator POS) Associative container Erases the element pointed toPos.
Size_type erase (const key_type & K) Associative container Erases the element whose key isK.
Void erase (iterator first, iterator last) Associative container Erases all elements in a range.
Void clear () Associative container Erases all of the elements.
Iterator find (const key_type & K) Associative container Finds an element whose key isK.
Const_iterator find (const key_type & K) const Associative container Finds an element whose key isK.
Size_type count (const key_type & K) Unique associative container Counts the number of elements whose key isK.
Iterator lower_bound (const key_type & K) Sorted associative container Finds the first element whose key is not lessK.
Const_iterator lower_bound (const key_type & K) const Sorted associative container Finds the first element whose key is not lessK.
Iterator upper_bound (const key_type & K) Sorted associative container Finds the first element whose key greaterK.
Const_iterator upper_bound (const key_type & K) const Sorted associative container Finds the first element whose key greaterK.
pair<iterator, iterator> equal_range(const key_type& k)
Sorted associative container Finds a range containing all elements whose key isK.
pair<const_iterator, const_iterator> equal_range(const key_type& k) const
Sorted associative container Finds a range containing all elements whose key isK.
data_type& operator[](const key_type& k) [3]
Map See below.
bool operator==(const map&,                 const map&)
Forward container Tests two maps for capacity. This is a global function, not a member function.
bool operator<(const map&,                const map&)
Forward container Lexicographical comparison. This is a global function, not a member function.

 
The following describes some common methods.

// Stu_map.cpp: defines the entry point of the console application. // # Include "stdafx. H "# include <iostream >#include <map> using namespace STD; bool fncomp (char LHS, char RHs) {return LHS <RHS;} struct classcomp {bool operator () (const char & LHS, const char & RHs) {return LHS <RHS ;}}; int _ tmain (INT argc, _ tchar * argv []) {Map <char, int> mymap; mymap ['a'] = 10; mymap ['B'] = 60; mymap ['C'] = 30; mymap ['D'] = 90; mymap ['E'] = 50; Map <char, int> second (mymap); Map <char, int> third (mymap. begin (), mymap. End (); Map <char, Int, classcomp> fourth; bool (* fn_pt) (char, char) = fncomp; Map <char, Int, bool (*) (char, char)> TH (fn_pt); Map <char, int >:: key_compare key_comp; Map <char, int >:: iterator it; it = mymap. begin (); For (it; it! = Mymap. end (); It ++) {cout <it-> first <":" <it-> second <Endl ;} cout <"==================================" <endl; second. clear (); Second ['a'] = 1002; second ['B'] = 10023; while (! Second. empty () {cout <second. begin ()-> first <"=>"; cout <second. begin ()-> second <Endl; second. erase (second. begin ());} cout <"==================================" <endl; mymap. insert (pair <char, int> ('F', 100); mymap. insert (pair <char, int> ('G', 200); cout <"F =>" <mymap. find ('F')-> second <Endl; cout <"G =>" <mymap. find ('G')-> second <Endl; cout <"==================================" <endl; key_comp = mymap. key_comp (); cout <"mymap contains: \ n"; char highest = mymap. rbegin ()-> first; // key value of last elementit = mymap. begin (); do {cout <(* it ). first <"=>" <(* it ). second <Endl;} while (key_comp (* It ++ ). first, highest); cout <Endl; return 0 ;}

Running result:

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.