您的位置:

mapinsert详解

一、返回值类型

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"