一、map.insert用法

map.insert用于向一個(gè)map中插入一個(gè)元素,返回一個(gè)pair,第一個(gè)元素是插入元素的迭代器,第二個(gè)元素是一個(gè)bool值,表示插入成功或者失敗。
#include
#include
二、map.insert初始化
如果我們想要初始化一個(gè)map,可以使用以下代碼:
#include
#include
三、map.insert 異常
在插入元素時(shí),可能會(huì)發(fā)生重復(fù)插入的情況,此時(shí)會(huì)返回一個(gè)bool值表示插入是否成功。
#include
#include
四、map.insert返回值
map.insert函數(shù)的返回值為一個(gè)pair,第一個(gè)元素是插入元素的迭代器,第二個(gè)元素為bool值表示插入是否成功。
#include
#include
五、map.insert()內(nèi)存泄漏
在C++中,使用new關(guān)鍵字動(dòng)態(tài)分配內(nèi)存時(shí),需要手動(dòng)調(diào)用delete來釋放內(nèi)存,否則會(huì)造成內(nèi)存泄漏。在使用map.insert()插入指針時(shí),也需要注意內(nèi)存泄漏的問題。
#include
#include
六、map.insert數(shù)組
map.insert函數(shù)還支持一次性插入一個(gè)數(shù)組,代碼如下:
#include
#include
七、map.insert 紅黑樹異常
由于map插入時(shí)需要保證鍵值唯一,因此map底層使用紅黑樹來實(shí)現(xiàn),如果插入造成非法操作,會(huì)引發(fā)紅黑樹異常。
#include
#include
八、map.insert(make_pair)
使用std::make_pair()也可以進(jìn)行插入元素,下面是使用make_pair插入元素的代碼:
#include
#include