所有元素會根據元素的鍵值自動被排序
- 元素的類型是pair,同時擁有鍵值和實值;map不允許兩個元素出現相同的鍵值
- pair 代碼
template <class T1,class T2>
struct pair{typedef T1 first_type;typedef T2 second_type;T1 first; //publicT2 second; //publicpair():first(T1()),second(T2()){};pair(const T1& a,const T2& b):first(a),second(b){};
};
- 不可以修改map的鍵值 但是可以修改實值
- map基于紅黑樹實現對應的函數
#include <iostream>#ifdef __STL_USE_EXCEPTIONS
#define __STL_TRY try
#define __STL_UNWIND(action) catch(...) { action; throw; }
#else
#define __STL_TRY
#define __STL_UNWIND(action)
#endif# ifdef __STL_EXPLICIT_FUNCTION_TMPL_ARGS
# define __STL_NULL_TMPL_ARGS <>
# else
# define __STL_NULL_TMPL_ARGS
# endiftypedef bool __rb_tree_color_type;
const __rb_tree_color_type __rb_tree_red = false; //紅色為0
const __rb_tree_color_type __rb_tree_black = true; //黑色為1struct __rb_tree_node_base{typedef __rb_tree_color_type color_type;typedef __rb_tree_node_base* base_ptr;color_type color; //節點顏色 非紅即黑base_ptr parent; //RB-Tree的許多操作 都是需要父節點的參與base_ptr left; //指向左節點base_ptr right; //指向右節點static base_ptr minimum(base_ptr x){while (x->left != 0){//二叉搜索樹的特性//一直向左走 就會找到最小值x = x->left;}return x;}static base_ptr maximum(base_ptr x){while(x->right != 0){//二叉搜索樹的特性//一直向右走 就會找到最大值x = x->right;}return x;}
};template <class Value>
struct __rb_tree_node : public __rb_tree_node_base{typedef __rb_tree_node<Value>* link_type;Value value_field; //節點值
};//基層迭代器
struct __rb_tree_base_iterator{typedef __rb_tree_node_base::base_ptr base_ptr;typedef std::bidirectional_iterator_tag iterator_category;typedef ptrdiff_t difference_type;base_ptr node; //用于和容器之間產生一個連接關系(make a reference)//以下實現于operator++內,因為再無其他地方會調用這個函數了void increment(){if (node->right != 0){ //如果有右節點,狀況一node = node->right; //就向右走while(node->left != 0){ //然后一直往左子樹前進node = node->left; //即為答案}} else{ //沒有右節點 狀況二base_ptr y = node->parent;//找出父節點while(node == y->right){ //如果現行節點本身是個右子節點node = y; //需要一直上溯 直到不為右子節點為止y = y->parent;}if (node->right != y){ //如果此時node的右子節點不等于此時的父節點node = y; //狀況三 此時的父節點即為解答} //否則 此時的node即為解答 狀況四}/*以上判斷 "若此時的右子節點不等于此時的父節點"是為了應對一種特殊的情況* 即:欲尋找的根節點的下一個節點,而此時根節點恰好沒有右子節點* 當然,上述的特殊做法需要配合RB-Tree根節點和特殊的header之間的特殊的關系*/}//以下實現于operator--內,因為再無其他地方會調用這個函數了void decrement(){//狀況一//如果是紅節點 且 父節點的父節點等于自己 右子節點即為答案//狀況一 發生于node為header的時候(亦即node為end()時)//注意:header的右子節點 即 mostright指向整棵樹的max節點if (node->color == __rb_tree_red && node->right->right == node){node = node->right;}//狀況二//如果有左子節點 令y指向左子節點;只有當y有右子節點的時候 一直往右走 到底,最后即為答案else if (node->left!=0){base_ptr y = node->left;while (y->right != 0){y = y->right;}node = y;} else{//狀況三//既不是根節點 也沒有左節點//找出父節點,當現行的節點身為左子節點時,一直交替往上走,直到現行節點不是左節點為止base_ptr y = node->parent;while(node == y->left){node = y;y = y->right;}node = y; //此時父節點即為答案}}
};//RB-Tree的正規迭代器
template <class Value,class Ref,class Ptr>
struct __rb_tree_iterator : public __rb_tree_base_iterator{typedef Value value_type;typedef Ref reference;typedef Ptr pointer;typedef __rb_tree_iterator<Value,Value&,Value*> iterator;typedef __rb_tree_iterator<Value,const Value&,const Value*> const_iterator;typedef __rb_tree_iterator<Value,Value&,Value*> self;typedef __rb_tree_node<Value>* link_type;__rb_tree_iterator(){}__rb_tree_iterator(link_type x){node = x;}__rb_tree_iterator(const iterator& it){node = it.node;}reference operator* () const {return link_type(node)->value_field; }#ifndef __SGI_STL_NO_ARROW_OPERATORreference operator->()const {return &(operator*());}
#endif //__SGI_STL_NO_ARROW_OPERATORself& operator++(){increment();return *this;}self operator++(int){self tmp = *this;increment();return tmp;}self& operator--(){decrement();return *this;}self operator--(int){self tmp = *this;decrement();return tmp;}};template<class T,class Alloc>
class simple_alloc{
public:static T* allocate(std::size_t n){return 0==n?0:(T*)Alloc::allocate(n * sizeof(T));}static T* allocate(void){return (T*)Alloc::allocate(sizeof (T));}static void deallocate(T* p,size_t n){if (n!=0){Alloc::deallocate(p,n * sizeof(T));}}static void deallocate(T* p){Alloc::deallocate(p,sizeof(T));}
};namespace Chy{template <class T>inline T* _allocate(ptrdiff_t size,T*){std::set_new_handler(0);T* tmp = (T*)(::operator new((std::size_t)(size * sizeof (T))));if (tmp == 0){std::cerr << "out of memory" << std::endl;exit(1);}return tmp;}template<class T>inline void _deallocate(T* buffer){::operator delete (buffer);}template<class T1,class T2>inline void _construct(T1 *p,const T2& value){new(p) T1 (value); //沒看懂}template <class T>inline void _destroy(T* ptr){ptr->~T();}template <class T>class allocator{public:typedef T value_type;typedef T* pointer;typedef const T* const_pointer;typedef T& reference;typedef const T& const_reference;typedef std::size_t size_type;typedef ptrdiff_t difference_type;template<class U>struct rebind{typedef allocator<U>other;};pointer allocate(size_type n,const void * hint = 0){return _allocate((difference_type)n,(pointer)0);}void deallocate(pointer p,size_type n){_deallocate(p);}void construct(pointer p,const T& value){_construct(p,value);}void destroy(pointer p){_destroy(p);}pointer address(reference x){return (pointer)&x;}const_pointer const_address(const_reference x){return (const_pointer)&x;}size_type max_size()const{return size_type(UINT_MAX/sizeof (T));}};
}template <class Key,class Value,class KeyOfValue,class Compare,class Alloc>
class rb_tree{
protected:typedef void* void_pointer;typedef __rb_tree_node_base* base_ptr;typedef __rb_tree_node<Value> rb_tree_node;typedef simple_alloc<rb_tree_node,Alloc>rb_tree_node_allocator;typedef __rb_tree_color_type color_type;
public:typedef Key key_type;typedef Value value_type;typedef value_type* pointer;typedef const value_type* const_pointer;typedef value_type& reference;typedef const value_type& const_reference;typedef rb_tree_node* link_type;typedef std::size_t size_type;typedef std::ptrdiff_t difference_type;
protected:link_type get_node(){return rb_tree_node_allocator::allocate();}void put_node(link_type p){return rb_tree_node_allocator::deallocate(p);}link_type create_node(const value_type& x){link_type tmp = get_node(); //配置空間__STL_TRY{Chy::allocator<Key>::construct(&tmp->value_field,x);//構造內容};__STL_UNWIND(put_node(tmp));return tmp;}link_type clone_node(link_type x){//復制一個節點的顏色和數值link_type tmp = create_node(x->value_field);tmp->color = x->color;tmp->left = 0;tmp->right = 0;return tmp;}void destroy_node(link_type p){Chy::allocator<Key>::destroy(&p->value_field); //析構內容put_node(p); //釋放內存}
protected://RB-tree只使用三筆數據表現size_type node_count; //追蹤記錄樹的大小 (節點的數量)link_type header; //實現上的小技巧Compare key_compare; //節點之間的鍵值大小的比較準則. 應該會是一個function object//以下三個函數用于方便獲取header的成員link_type& root() const{return (link_type&)header->parent;}link_type& left_most() const{return (link_type&)header->left;}link_type& right_most() const{return (link_type&)header->right;}//以下六個函數用于方便獲得節點x的成員static link_type& left(link_type x){ return(link_type&)x->left;}static link_type& right(link_type x){ return(link_type&)x->right;}static link_type& parent(link_type x){ return(link_type&)x->parent;}static reference value(link_type x){ return x->value_field;}static const Key& key(link_type x){ return KeyOfValue()(value(x));}static color_type& color(link_type x){return (color_type&) (x->color);}//獲取極大值和極小值 node class有實現此功能static link_type minimum(link_type x){return (link_type) __rb_tree_node_base::minimum(x);}static link_type maximum(link_type x){return (link_type) __rb_tree_node_base::maximum(x);}//迭代器typedef __rb_tree_iterator<value_type,reference,pointer>iterator;
public:iterator __insert(base_ptr x,base_ptr y,const value_type& v);link_type __copy(link_type x,link_type p);void __erase(link_type x);void clear() {if (node_count != 0) {__erase(root());left_most() = header;root() = 0;right_most() = header;node_count = 0;}}void init(){header = get_node(); //產生一個節點空間 令header指向它color(header) = __rb_tree_red;//令header為紅色 用于區分header和root,在iterator的operator++中root() == 0;left_most() = header; //令header的左子節點等于自己right_most() = header; //令header的右子節點等于自己}
public://allocation / deallocationrb_tree(const Compare& comp = Compare()): node_count(0),key_compare(comp){init();}~rb_tree(){clear();put_node(header);}rb_tree<Key,Value,KeyOfValue,Compare,Alloc>&operator==(const rb_tree<Key,Value,KeyOfValue,Compare,Alloc>&x);
public://accessorsCompare key_comp() const {return key_compare;}iterator begin() {return left_most();} //RB樹的起頭為最左(最小)節點處iterator end(){return header;} //RB樹的終點為header所指處bool empty() const {return node_count == 0;}size_type size() const {return node_count;}size_type max_size() const {return size_type (-1);}
public://insert/erase//將x插入到RB-Tree中 (保持節點的獨一無二)std::pair<iterator,bool> insert_unique(const value_type& x);//將x插入到RB-Tree中 (允許節點數值重復)iterator insert_equal(const value_type& x);//尋找鍵值為k的節點iterator find(const value_type& k);
};//插入新的數值 節點鍵值允許重復
//注意:返回的是一個RB-Tree的迭代器,指向的是新增的節點
template <class Key,class Value,class KeyOfValue,class Compare,class Alloc>
typename rb_tree<Key,Value,KeyOfValue,Compare,Alloc>::iterator
rb_tree<Key,Value,KeyOfValue,Compare,Alloc>::insert_equal(const value_type &v) {link_type y = header;link_type x = root(); //根節點開始while(x != 0){ //根節點開始 從上往下尋找適當的插入節點y = x;//如果當前根節點比 輸入的v大,則轉向左邊,否則轉向右邊x = key_compare(KeyOfValue()(v), key(x)) ? left(x) : right(x);}//x為新值插入點 y為插入點的父節點 v為新值return __insert(x,y,v);
}//插入新的數值 節點鍵值不允許重復
//注意:返回結果是pair類型,第一個元素是一個RB-Tree的迭代器,指向的是新增的節點;第二個參數表示插入成功與否
template <class Key,class Value,class KeyOfValue,class Compare,class Alloc>
std::pair<typename rb_tree<Key,Value,KeyOfValue,Compare,Alloc>::iterator,bool>
rb_tree<Key,Value,KeyOfValue,Compare,Alloc>::insert_unique(const value_type &v) {link_type y = header;link_type x = root(); //從根節點開始bool comp = true;while(x != 0){ //從根節點開始 往下尋找適當的插入點y = x;comp = key_compare(KeyOfValue()(v), key(x)); //v鍵值小于目前節點的鍵值x = comp ? left(x) : right(x); //遇"大"則向左 遇"小"則向右}//離開while循環之后 y所指的即 插入點之父節點(此時它必為葉子結點)iterator j = iterator(y); //迭代器j指向插入點的父節點yif (comp){//如果while循環時候,判定comp的數值,如果comp為真(表示遇到大的元素,將插入左側)//如果插入節點的父節點是最左側的節點//x為插入點,y為插入節點的父節點,v表示新值if (j == begin()){return std::pair<iterator,bool>(__insert(x,y,v), true);} else{//插入節點的父節點不是最左側的節點//調整j 回頭準備測試--j;}if (key_compare(key(j.node),KeyOfValue()(v))){//小于新值(表示遇到小的數值,將插在右側)return std::pair<iterator,bool>(__insert(x,y,v), true);}}//至此 表示新值一定和樹中的鍵值重復 就不應該插入新的數值return std::pair<iterator,bool>(j, false);
}//真正的插入執行程序 __insert()
template <class Key,class Value,class KeyOfValue,class Compare,class Alloc>
typename rb_tree<Key,Value,KeyOfValue,Compare,Alloc>::iterator
rb_tree<Key,Value,KeyOfValue,Compare,Alloc>::__insert(base_ptr x_, base_ptr y_, const value_type &v) {//參數x_為新的插入點 參數y_為插入點的父節點 參數v為新值link_type x = (link_type)x_;link_type y = (link_type)y_;link_type z ;//key_compare 是鍵值大小的比較準則,應該是一個function objectif (y == header||x != 0||key_compare(KeyOfValue()(v),key(x))){z = create_node(v); //產生一個新的節點//當y即為header的時候,leftmost = z;if (y == header){root() = z;right_most() = z;} else if (y == left_most()){//y為最左節點//維護leftmost() 使其永遠指向最左節點left_most() = z;} else{z = create_node(v);//產生一個新的節點//讓新節成為插入點的父節點y的右子節點right(y) = z;if (y == right_most()){ //維護rightmost()讓其永遠指向最右的節點right_most() = z;}}parent(z) = y; //設定新節點的父節點left(z) = 0; //設定新節點的左子節點right(z) = 0; //設定新節點的右子節點//修改顏色//參數一為新增節點 ;參數二 為root__rb_tree_rebalance(z,header->parent);++node_count;//返回一個迭代器 指向新的節點return iterator(z);}
}//全局函數
//新節點必須為紅色,如果插入出父節點同樣為紅色,就需要進行樹形旋轉
inline void __rb_tree_rotate_left(__rb_tree_node_base* x,__rb_tree_node_base*& root){//x為旋轉點__rb_tree_node_base* y = x->right;//令y為旋轉點的右子節點x->right = y->left;if (y->left != 0){//回馬槍設定父親節點y->left->parent = x;}y->parent = x->parent;//令y完全替代x的地位 (需要將x對其父節點的關系完全接收回來)if (x == root){root = y; //x為根節點} else if (x == x->parent->left){x->parent->left = y; //x為其父節點的左子節點} else{x->parent->right = y; //x為其父節點的右子節點}y->left = x;x->parent = y;
}//全局函數
//新節點必須為紅色,如果插入出父節點同樣為紅色,就需要進行樹形旋轉
inline void __rb_tree_rotate_right(__rb_tree_node_base* x,__rb_tree_node_base*& root){//x為旋轉點__rb_tree_node_base* y = x->left; //y為旋轉點的左子節點x->left = y->right;if (y->right != 0){y->right->parent = x;}y->parent = x->parent;//令y完全替代x的地位if(x == root){root = y;} else if (x == x->parent->right){x->parent->right = y;} else{x->parent->left = y;}y->parent = x;x->parent = y;
}//調整RB_tree 插入節點之后,需要進行調整(顏色/翻轉)從而滿足要求
inline void __rb_tree_balance(__rb_tree_node_base* x,__rb_tree_node_base*& root){x->color = __rb_tree_red; //新節點的顏色必須是紅色的while(x!=root && x->parent->color == __rb_tree_red){//父節點為紅色的//父節點為祖父節點的左子節點if (x->parent == x->parent->parent->left){//令y為伯父節點__rb_tree_node_base* y = x->parent->right;if (y && y->color == __rb_tree_red){ //伯父節點存在 且為紅x->parent->color = __rb_tree_black;//更改父節點的顏色為黑y->color = __rb_tree_black;//更改父節點的顏色為黑x->parent->parent->color = __rb_tree_red;//更改祖父節點的顏色為紅x = x->parent->parent;} else{//無伯父節點 或者伯父節點的顏色為黑if (x == x->parent->right){//新節點為父節點的右子節點x = x->parent;//第一次參數為左旋節點__rb_tree_rotate_left(x,root);}x->parent->color = __rb_tree_black;//改變顏色x->parent->parent->color = __rb_tree_red;//第一次參數為右旋節點__rb_tree_rotate_right(x->parent->parent,root);}} else{//父節點為祖父節點的右子節點__rb_tree_node_base* y = x->parent->parent->left; //令y為伯父節點if (y && y->color == __rb_tree_red){ //存在伯父節點,且為紅x->parent->color = __rb_tree_black;//更改父節點為黑y->color = __rb_tree_black;//更改伯父節點為黑x->parent->parent->color = __rb_tree_red; //更改祖父節點為紅x = x->parent->parent; //準備繼續往上層檢查} else{//無伯父節點 或者伯父節點 為黑if (x == x->parent->left){//新節點 為 父節點的左子節點x = x->parent;__rb_tree_rotate_right(x,root); //第一參數為右旋轉點}x->parent->color = __rb_tree_black;//改變顏色x->parent->parent->color = __rb_tree_red;//第一參數為左旋點__rb_tree_rotate_left(x->parent->parent,root);}}} //while結束root->color = __rb_tree_black;
}//元素查找程序
template <class Key,class Value,class KeyOfValue,class Compare,class Alloc>
typename rb_tree<Key,Value,KeyOfValue,Compare,Alloc>::iterator
rb_tree<Key,Value,KeyOfValue,Compare,Alloc>::find(const value_type &k) {link_type y = header; //last node which is not less than klink_type x = root(); //current nodewhile(x != 0){//key_compare 是節點大小的比較準則 function objectif (!key_compare(key(x),k)){//進行到這里 表示x的數值大于k 。遇到大的數值向左走y = x,x = left(x);} else{x = right(x);}}iterator j = iterator (y);return (j == end() || key_compare(k,key(j.node))) ? end() : j;
}/************************************************************************************************************************/
//注意:以下的identify定義于
template <class T>
struct identify : public std::unary_function<T,T>{const T& operator()(const T& x) const {return x;}
};template<typename _Pair>
struct _Select1st: public std::unary_function<_Pair, typename _Pair::first_type>
{typename _Pair::first_type&operator()(_Pair& __x) const{ return __x.first; }
};template <class Key,class T,class Alloc,class Compare = std::less<Key>>
class map{
public:typedef Key key_type;//鍵值型別typedef T data_type;//數據(實值)型別typedef T mapped_type;typedef std::pair<const Key,T>value_type; //元素型別(鍵值/實值)//鍵值比較函數typedef Compare key_compare;//以下定義一個functor 其作用就是調用"元素比較函數"class value_compare : public std::binary_function<value_type,value_type,bool>{friend class map<Key,T,Compare,Alloc>;protected:Compare comp;value_compare(Compare c):comp(c){}public:bool operator()(const value_type& x,const value_type& y)const{return comp(x.first,y.first);}};
private://定義表述型別 使用map元素的型別(pair)作為第一性別,作為紅黑樹節點的鍵值型別typedef rb_tree<key_type,value_type,_Select1st<value_type>,key_compare,Alloc>rep_type;rep_type t; //使用紅黑樹(RB-Tree)實現map
public:typedef typename rep_type::pointer pointer;typedef typename rep_type::const_pointer const_pointer;typedef typename rep_type::reference reference;typedef typename rep_type::const_reference const_reference;//map迭代器無法執行寫入操作,因為map的元素有一定的次序安排,不允許用戶在任意處進行寫入操作typedef typename rep_type::iterator iterator;typedef typename rep_type::const_iterator const_iterator;typedef typename rep_type::reverse_iterator reverse_iterator;typedef typename rep_type::const_reverse_iterator const_reverse_iterator;typedef typename rep_type::size_type size_type;typedef typename rep_type::difference_type difference_type;//allocation/deallocation//map使用RB-Tree的insert_unique() 要求插入的元素都不可以重復//multimap 使用 insert_equal() 允許相同鍵值的存在//構造函數map():t(Compare()){}explicit map(const Compare& comp) : t(comp){}template<class InputIterator>map(InputIterator first,InputIterator last) : t(Compare()){t.insert_unique(first,last);}template<class InputIterator>map(InputIterator first,InputIterator last,const Compare& comp) : t(comp){t.insert_unique(first,last);}map(const map<Key,Compare,Alloc>&x):t(x.t){}map<Key,Compare,Alloc>& operator=(const map<Key,Compare,Alloc>&x){t = x.t;return *this;}//map進行函數的包裝//accessorskey_compare key_comp()const{ return t.key_comp();}//需要注意 map使用的value_comp 事實上為RB-Tree的key_comp()value_compare value_comp() const {return value_compare(t.key_comp());}iterator begin() {return t.begin();}const_iterator begin() const {return t.begin();}iterator end() {return t.end();}const_iterator end() const {return t.end();}reverse_iterator rbegin() {return t.rbegin();}const_reverse_iterator rbegin() const {return t.rbegin();}reverse_iterator rend() {return t.rend();}const_reverse_iterator rend() const{return t.rend();}bool empty() const {return t.empty();}size_type size() const {return t.size();}size_type max_size() const {return t.max_size();}//注意以下 下標操作符號T& operator[](const key_type& k){return (*((insert(value_type(k,T()))).first)).second;}void swap(map<Key,Compare,Alloc>& x){t.swap(x.t);}//insert / erase
// typedef std::pair<iterator,bool>pair_iterator_bool;std::pair<iterator,bool>insert(const value_type& x){return t.insert_unique(x);}iterator insert(iterator position,const value_type& x){return t.insert_unique(position,x);}template <class InputIterator>void insert(InputIterator first,InputIterator last){t.insert_unique(first,last);}void erase(iterator position){t.erase(position);}size_type erase(const key_type& x){return t.erase(x);}void erase(iterator first,iterator last){t.erase(first,last);}void clear(){t.clear();}//map operationsiterator find(const key_type& x)const {return t.find(x);}const_iterator find(const key_type& x) {return t.find(x);}size_type count(const key_type& x)const {return t.count(x);}iterator lower_bound(const key_type&x) { return t.lower_bound(x);}const_iterator lower_bound(const key_type&x) const{ return t.lower_bound(x);}iterator upper_bound(const key_type&x) { return t.upper_bound(x);}const_iterator upper_bound(const key_type&x) const{ return t.upper_bound(x);}std::pair<iterator,iterator>equal_range(const key_type&x){return t.equal_range(x);}std::pair<const_iterator,const_iterator>equal_range(const key_type&x)const{return t.equal_range(x);}//以下的__STL_NULL_TMPL_ARGS 被定義為<>friend bool operator== __STL_NULL_TMPL_ARGS (const map&,const map&);friend bool operator< __STL_NULL_TMPL_ARGS (const map&,const map&);
};template <class Key,class Compare,class Alloc>
inline bool operator==(const map<Key,Compare,Alloc>&x,const map<Key,Compare,Alloc>&y){return x.t == y.t;
}template <class Key,class Compare,class Alloc>
inline bool operator<(const map<Key,Compare,Alloc>&x,const map<Key,Compare,Alloc>&y){return x.t < y.t;
}
#include <iostream>
#include <map>
#include <string>int main(){std::map<std::string,int>s_i_map;s_i_map[std::string("number1")] = 1;s_i_map[std::string("number2")] = 2;s_i_map[std::string("number3")] = 3;s_i_map[std::string("number4")] = 4;std::pair<std::string,int>value(std::string("david"),5);s_i_map.insert(value);std::map<std::string,int>::iterator map_iterator = s_i_map.begin();for ( ;map_iterator != s_i_map.end();++map_iterator) {std::cout << map_iterator->first << ' ';std::cout << map_iterator->second << std::endl;}int number = s_i_map[std::string("number2")];std::cout << number << std::endl;map_iterator = s_i_map.find(std::string("number2"));if (map_iterator == s_i_map.end()){std::cout << "number2 not found!" << std::endl;}//通過map迭代器修改value 但是不可以修改keyint number2 = s_i_map[std::string("12344555")];std::cout << number2 << std::endl;}
- 下標操作符用法有兩種:1,作為左值使用(內容可以被改變);2,作為右值使用(內容不可以被修改)
- 左值和右值都適用的關鍵在于,返回數值采用 by reference 傳遞的形式
- 無論如何,下標操作符都根據鍵值找到與之對應的實值
std::map<std::string,int>simap; //以string作為鍵值,以int作為實值simap[std::string("jjhou")] = 1; //左值運用int right_value = simap[std::string("jjhou")]; //右值運用
#include <iostream>template<class Key,class T,class Alloc,class Compare = std::less<Key>>
class map{
public:typedef Key key_type; //鍵值類型typedef std::pair<const Key,T>value_type;//元素類型 (鍵值/實值)public:T& operator[] (const key_type& k){return (*((inserter(value_type(k,T()))).first)).second;}
};
- 對于上式operator[] 講解,首先根據鍵值和實值做出一個元素,但是考慮到實值是未知的,所以調用實值的構造函數,產生一個和實值型別相同的暫時對象,這也就是value_type(k,T())這一句的含義。再將這個元素插入到map里面,inserter(value_type(k,T()),insert返回的是一個pair類型的結構,第一個元素是第一個迭代器,指向的是插入妥當的新元素或者指向的是插入失敗點(鍵值重復的)舊的元素
- 注意如果下標操作符作為左值使用(通常表示要添加的元素),我們正好以此"實值待填"的元素將位置卡號;
- 如果下標操作符號作為右值使用(通常代表需要根據鍵值得到與之對應的實值),此時的插入操作所返回的pair的第一個元素(迭代器)指向的是鍵值符合的舊元素
- 取得操作操作所返回的pair的第一元素,inserter(value_type(k,T())).first? 是一個迭代器
- 提領迭代器 *(inserter(value_type(k,T())).first) 得到一個map元素,取其第二個元素,即得到實值 *(inserter(value_type(k,T())).first).second
- 注意這個實值是通過by reference的方式傳遞的,因此它作為左值和右值都可以
?參考鏈接
- C++ STL源碼剖析之map、multimap、initializer_list - 知乎