一、返回值類型
mapinsert函數用於向map中插入一條數據,其返回值類型為std::pair。其中,iterator指向新插入的元素位置,bool值表示插入是否成功。
二、mapinsert的使用方法
在使用mapinsert函數之前,需要先定義一個map容器,並添加需要插入的數據:
std::map<int, std::string> myMap; // 定義map容器
myMap.insert({1,"hello"}); // 向map容器中添加數據
使用insert函數時,需要傳入一個std::pair類型的參數,其中第一個值為key,第二個值為value。如果在插入時出現key衝突,即已經存在該key的元素,則插入失敗。此時,insert函數返回值為一個std::pair類型,其bool值為false,用於表示插入失敗。
auto res = myMap.insert({1,"world"}); // 嘗試向map容器中插入衝突數據
if(res.second) { // 插入成功
std::cout << "insert success" << std::endl;
} else { // 插入失敗
std::cout << "insert failed" << std::endl;
}
三、mapinsert插入多個數據
除了可以使用insert函數逐個插入數據,還可以一次性向map中插入多個數據。這可以通過使用std::map::insert函數的迭代器範圍版本實現:
std::map<int, std::string> myMap; // 定義map容器
std::map<int, std::string> newMap = {
{1,"hello"},
{2,"world"}
}; // 定義新的插入數據
myMap.insert(newMap.begin(), newMap.end()); // 將新數據插入到原map容器中
需要注意的是,如果新插入的數據中有與原map容器中已存在的數據key相同的元素,則會導致插入失敗,此時insert函數仍然返回一個std::pair類型,其bool值為false。
四、利用返回值判斷插入結果
在使用mapinsert函數插入數據時,可以通過返回值的bool類型判斷插入是否成功。如果插入成功,bool值為true;如果插入失敗,bool值為false。
std::map<int, std::string> myMap; // 定義map容器
auto res1 = myMap.insert({1,"hello"}); // 新數據插入
auto res2 = myMap.insert({1,"world"}); // 衝突數據插入
if(res1.second) { // 插入成功
std::cout << "insert success" << std::endl;
} else { // 插入失敗
std::cout << "insert failed" << std::endl;
}
if(res2.second) { // 插入成功
std::cout << "insert success" << std::endl;
} else { // 插入失敗
std::cout << "insert failed" << std::endl;
}
上述代碼中,第一次插入成功,第二次插入失敗。
五、mapinsert函數的返回值使用
除了用於判斷插入操作是否成功,函數返回值還可以用於改變map容器中已有元素的值。如果使用insert函數插入的數據已經存在於map中,insert函數實際上並不會插入新的數據。但是如果在insert函數中修改已有元素的值,map容器中的相應元素值就會改變。
std::map<int,std::string> myMap = {
{1,"hello"},
{2,"world"}
};
auto res = myMap.insert({1,"new hello"}); // 由於key值已經存在,不會插入新數據;而是修改原數據的值
if(!res.second) {
res.first->second = "new hello";
}
std::cout << myMap[1] << std::endl; // 輸出 "new hello"
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/158364.html