mapinsert详解

发布时间:2023-05-19

一、返回值类型

mapinsert 函数用于向 map 中插入一条数据,其返回值类型为 std::pair<iterator,bool>。其中,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"