C++编程笔记:错误使用insert方法更新C++ std::map数据
💻

C++编程笔记:错误使用insert方法更新C++ std::map数据

Published
发布:2024-08-28
Last Updated
修改:2024-09-12

背景任务

在开发中使用C++编程时,需要对map类型实例中已存在的key-value数据进行更新,即更新其中某个已存在key-value数据中的value值。
相应代码如下所示:
std::map<std::string, std::vector<uint8_t>> dataStore;
其中dataSatorestd::map实例变量,其key类型为std::stringvalue 类型为std::vector<uint8_t>

错误问题

针对上述背景任务,一开始使用了std::map类型内置的insert 方法去更新数据:
// 第一次调用 dataStore.insert({"some_key", std::vector<uint8_t>(data_ptr1, data_ptr1 + data_size1)}); ...... // 第二次调用 dataStore.insert({"some_key", std::vector<uint8_t>(data_ptr2, data_ptr2 + data_size2)});
在调试过程中发现在第一次调用insert 方法时,对应keysome_keyvalue 值会成功置于变量dataStore 中,但在第二次调用insert 方法时,其值没有变化更新为最新值。后来发现是因为这里不应该使用insert 方法。

std::map Insert

insert 方法是C++ std::map中内置方法用于在map中插入数据,其常用语法为:
std::pair<iterator, bool> map_name.insert({key, value})
当map中没有对应的{key, value} 数据时,会将该数据插入到map中;
当map中已经有对应{key, value} 数据时,不会影响已有数据。
 
其返回值为std::pair 其第一个元素为指向map中已经插入或已存在key-value数据对的iterator ;第二个元素为bool值,其为true 时表示插入了新数据,为false 时表示数据已存在。

解决方法

更新map中的已有数据,可以:
  1. 使用操作符[] 和赋值语句:
    1. dataStore["some_key"] = std::vector<uint8_t>(data_ptr2, data_ptr2 + data_size2)}
  1. 使用方法insert_or_assign ,C++ 17:
    1. dataStore.insert_or_assign(std::vector<uint8_t>(data_ptr2, data_ptr2 + data_size2)});
上述方法可以更新map中已存在的数据,或者在没有相应数据时插入新数据。

参考链接

  1. https://www.geeksforgeeks.org/map-insert-in-c-stl/
  1. https://www.geeksforgeeks.org/how-to-update-value-of-key-in-map-in-cpp/