STL map中subscript操作符用法

來源:互聯網
上載者:User

map是STL中基於紅/黑樹狀結構的一種資料結構,該結構的元素是pair<key,value>,其中key是元素的索引值,搜尋時使用,value是元素的實值,是這棵樹中真正要儲存的東西。map的函數基本是基於底層的紅/黑樹狀結構的,也有一些是自有函數,比如subscript操作符,即“[ ]”。

作出以下函數驗證subscript操作符:

map<string,int> imap;pair<string,int> tmp("A",1);imap.insert(tmp);imap[string("B")]=2;//當“[ ]”返回的元素作為左值運用時,如果沒有‘B’,則在紅/黑樹狀結構中插入這個節點,如果有‘B’,則返回指向這個節點的迭代器。int second=imp[string("C")];map<string,int>::iterator imapIter=imap.begin();while(imapIter!=imap.end()){  cout<<(*imapIter).first<<" "<<(*imapIter).second<<endl;  imapIter++;}

以上程式的結果是:

A 1B 2C 0

程式表明subscirpt操作符不單單是個提領的過程,它裡面隱含著插入操作,考察map中subscript源碼: 

template<class T>public: T& operator[] (const key_type &k){   return (*((insert(value_type(k,T()))).first)).second}

所以,使用map中的下標操作符要注意了,裡面是隱含有插入的,不分左值情況和右值情況。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.