C++中map的概念,與簡單操作


 來源:http://blog.csdn.net/wallwind/article/details/6876892
C++map學習
 

map<Key, Data, Compare, Alloc>

 

map是一種關聯容器,存儲相結合形成的一個關鍵值和映射值的元素。Map 是一種Pair Associative Container,意味着它的值類型為 pair<const Key, Data>. 而且也是 Unique Associative Container, 也就是任何兩個元素沒有相同的key值。

map具有重要的屬性,就是在map對象中插入一個新元素不指向現有元素的迭代器失效。從map上刪除一個元素,也沒有任何迭代器失效,除非,當然,實際上指向正在被刪除的元素的迭代器。

 

1、例子

[cpp] view plain copy
 
  1. struct ltstr  
  2. {  
  3.   bool operator()(const char* s1, const char* s2) const  
  4.   {  
  5.     return strcmp(s1, s2) < 0;  
  6.   }  
  7. };  
  8.   
  9. int main()  
  10. {  
  11.   map<const char*, int, ltstr> months;  
  12.     
  13.   months["january"] = 31;  
  14.   months["february"] = 28;  
  15.   months["march"] = 31;  
  16.   months["april"] = 30;  
  17.   months["may"] = 31;  
  18.   months["june"] = 30;  
  19.   months["july"] = 31;  
  20.   months["august"] = 31;  
  21.   months["september"] = 30;  
  22.   months["october"] = 31;  
  23.   months["november"] = 30;  
  24.   months["december"] = 31;  
  25.     
  26.   cout << "june -> " << months["june"] << endl;  
  27.   map<const char*, int, ltstr>::iterator cur  = months.find("june");  
  28.   map<const char*, int, ltstr>::iterator prev = cur;  
  29.   map<const char*, int, ltstr>::iterator next = cur;      
  30.   ++next;  
  31.   --prev;  
  32.   cout << "Previous (in alphabetical order) is " << (*prev).first << endl;  
  33.   cout << "Next (in alphabetical order) is " << (*next).first << endl;  
  34. }  

 

2、定義形式

[cpp] view plain copy
 
  1. template < class Key, class T, class Compare = less<Key>,  
  2.            class Allocator = allocator<pair<const Key,T> > > class map;  

 

3、模板參數具有以下涵義:

key:關鍵值的類型。在map對象中的每個元素是通過該關鍵值唯一確定元素的。
T:映射值的類型。在map中的每個元素是用來儲存一些數據作為其映射值。
compare:Comparison類:A類鍵的類型,它有兩個參數,並返回一個bool。表達comp(A,B),comp是這比較類A和B是關鍵值的對象,應返回true,如果是在早先的立場比B放置在一個嚴格弱排序操作。這可以是一個類實現一個函數調用運算符或一個函數的指針(見一個例子構造)。默認的對於<KEY>,返回申請小於操作符相同的默認值(A <B)。
Map對象使用這個表達式來確定在容器中元素的位置。以下這個規則在任何時候都排列在map容器中的所有元素。
Allocator:用於定義存儲分配模型分配器對象的類型。默認情況下,分配器類模板,它定義了最簡單的內存分配模式,是值獨立的

 

[cpp] view plain copy
 
  1. map<Key,T>::iterator it;  
  2. (*it).first;             // 指向key值(of type Key)  
  3. (*it).second;            // 映射的值(of type T)  
  4. (*it);                   // the "element value" (of type pair<const Key,T>)    //看到此處懵逼啊有木有!!(*it)到底該如何表述,查CPLUSPLUS  pair  如下:
  5. -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
  6. class template
  7. <utility>
  8. std::pair
  9. template <class T1, class T2> struct pair;
    Pair of values
    This class couples together a pair of values, which may be of different types (T1 and T2). The individual values can be accessed through its public members first and second.  是一對值

    Pairs are a particular case of tuple.    pairs是一特定的元祖,然后我搜了tuple,
  10. class template
    <tuple>

    std::tuple

    template <class... Types> class tuple;
    Tuple
    A tuple is an object capable to hold a collection of elements. Each element can be of a different type.   tuple是一個能夠容納元素集合的obiect。每個元素可以是不同的類型。
  11. it本身是迭代器, (*it)默認指迭代器內部第一個鍵值對(tuple元組)    //尼瑪,看半天才知道此處專業叫法是迭代器里邊的‘解引用操作符’,指向其內部元素!!

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
也可以如下表達:

[cpp] view plain copy
 
  1. it->first;               // same as (*it).first   (the key value)  
  2. it->second;              // same as (*it).second  (the mapped value)  


 

 

4、成員變量和成員函數

Member Where defined Description
key_type Associative Container map中的key類型
data_type Pair Associative Container key關聯的值類型
value_type Pair Associative Container 對象類型, pair<const key_type, data_type>,存儲在map中
key_compare Sorted Associative Container Function object 通過順序比較
value_compare Sorted Associative Container Function object that compares two values for ordering.
pointer Container Pointer to T.
reference Container Reference to T
const_reference Container Const reference to T
size_type Container An unsigned integral type.
difference_type Container A signed integral type.
iterator Container Iterator used to iterate through a map[1]
const_iterator Container Const iterator used to iterate through a map.
reverse_iterator Reversible Container Iterator used to iterate backwards through a map.[1]
const_reverse_iterator Reversible Container Const iterator used to iterate backwards through amap.
iterator begin() Container Returns an iterator pointing to the beginning of the map.
iterator end() Container Returns an iterator pointing to the end of the map.
const_iterator begin() const Container Returns a const_iterator pointing to the beginning of themap.
const_iterator end() const Container Returns a const_iterator pointing to the end of the map.
reverse_iterator rbegin() Reversible Container Returns a reverse_iterator pointing to the beginning of the reversed map.
reverse_iterator rend() Reversible Container Returns a reverse_iterator pointing to the end of the reversed map.
const_reverse_iterator rbegin() const Reversible Container Returns a const_reverse_iterator pointing to the beginning of the reversed map.
const_reverse_iterator rend() const Reversible Container Returns a const_reverse_iterator pointing to the end of the reversed map.
size_type size() const Container Returns the size of the map.
size_type max_size() const Container Returns the largest possible size of the map.
bool empty() const Container true if the map's size is 0.
key_compare key_comp() const Sorted Associative Container Returns the key_compare object used by the map.
value_compare value_comp() const Sorted Associative Container Returns the value_compare object used by the map.
map() Container Creates an empty map.
map(const key_compare& comp) Sorted Associative Container Creates an empty map, using comp as thekey_compare object.
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, using compas thekey_compare object.
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 Inserts x into the map.
iterator insert(iterator pos,
                const value_type& x)
Unique Sorted Associative Container Inserts x into the map, using pos as a hint to where it will be inserted.
template <class InputIterator>
void insert(InputIterator, InputIterator)
[2]
Unique Sorted Associative Container Inserts a range into the map.
void erase(iterator pos) Associative Container Erases the element pointed to by pos.
size_type erase(const key_type& k) Associative Container Erases the element whose key is k.
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 is k.
const_iterator find(const key_type& k) const Associative Container Finds an element whose key is k.
size_type count(const key_type& k) Unique Associative Container Counts the number of elements whose key is k.
iterator lower_bound(const key_type& k) Sorted Associative Container Finds the first element whose key is not less thank.
const_iterator lower_bound(const key_type& k) const Sorted Associative Container Finds the first element whose key is not less thank.
iterator upper_bound(const key_type& k) Sorted Associative Container Finds the first element whose key greater than k.
const_iterator upper_bound(const key_type& k) const Sorted Associative Container Finds the first element whose key greater than k.
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 equality. 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.
[cpp] view plain copy
 
  1.    
[cpp] view plain copy
 
  1. 下面展示了常用的一些方法。<p>// stu_map.cpp : 定義控制台應用程序的入口點。  
  2. //  
  3.   
  4. #include "stdafx.h"  
  5. #include <iostream>  
  6. #include <map>  
  7. using namespace std;  
  8.   
  9. bool fncomp(char lhs,char rhs)  
  10. {  
  11.     return lhs<rhs;  
  12. }  
  13. struct classcomp   
  14. {  
  15.     bool operator()(const char& lhs,const char& rhs)  
  16.     {  
  17.         return lhs<rhs;  
  18.     }  
  19. };  
  20. int _tmain(int argc, _TCHAR* argv[])  
  21. {  
  22.     map<char,int> mymap;  
  23.     mymap['a']=10;  
  24.     mymap['b']=60;  
  25.     mymap['c']=30;  
  26.     mymap['d']=90;  
  27.     mymap['e']=50;  
  28.   
  29.     map<char,int> second(mymap);  
  30.     map<char,int> third(mymap.begin(),mymap.end());  
  31.     map<char,int,classcomp> fourth;  
  32.     bool(*fn_pt)(char,char)=fncomp;  
  33.     map<char,int,bool(*)(char,char)> fifth(fn_pt);  
  34.     map<char,int>::key_compare key_comp;  
  35.     map<char,int>::iterator it;  
  36.     it=mymap.begin();  
  37.     for (it;it!=mymap.end();it++)  
  38.     {  
  39.         cout<<it->first<<":"<<it->second<<endl;  
  40.     }  
  41.     cout<<"================================="<<endl;  
  42.     second.clear();  
  43.     second['a']=1002;  
  44.     second['b']=10023;  
  45.     while (!second.empty())  
  46.     {  
  47.         cout << second.begin()->first << " => ";  
  48.         cout << second.begin()->second << endl;  
  49.         second.erase(second.begin());  
  50.     }  
  51.     cout<<"================================="<<endl;  
  52.     mymap.insert(pair<char,int>('f',100) );  
  53.     mymap.insert(pair<char,int>('g',200) );  
  54.     cout<<"f => " <<mymap.find('f')->second<<endl;  
  55.     cout<<"g => " <<mymap.find('g')->second<<endl;  
  56.   
  57.     cout<<"================================="<<endl;  
  58.     key_comp=mymap.key_comp();  
  59.     cout << "mymap contains:\n";  
  60.   
  61.     char highest=mymap.rbegin()->first;     // key value of last element  
  62.   
  63.     it=mymap.begin();  
  64.     do {  
  65.         cout << (*it).first << " => " << (*it).second << endl;  
  66.     } while ( key_comp((*it++).first, highest) );  
  67.   
  68.     cout << endl;  
  69.     return 0;  
  70. }  
  71.   
  72. </p>  


運行結果:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM