县区社保经办网站建设,北京网站优化策略,网页设计与制作教程第二版张晓蕾课后答案,通城做网站公司由于std::map中#xff0c;元素的key是唯一的#xff0c;我们经常遇到这样的场景#xff0c;向map中插入元素时#xff0c;先检测map指定的key是否存在#xff0c;不存在时才做插入操作#xff0c;如果存在#xff0c;直接取出来使用#xff0c;或者key不存在时#x…由于std::map中元素的key是唯一的我们经常遇到这样的场景向map中插入元素时先检测map指定的key是否存在不存在时才做插入操作如果存在直接取出来使用或者key不存在时做插入操作存在时做更新操作。
通用的做法可以直接用emplace操作判断指定的key是否存在如果不存在则插入元素当元素存在的时候emplace依然会构造一次带待插入元素判断不需要插入后将该元素析构这样导致的后果是产生了多余的构造和析构操作。
鉴于此C17引入了std::try_emplace在参数列表中把key和value分开该方法会检测指定的key是否存在如果存在什么也不做不存在则插入相应的value。
此外C17为map容器还新增了insert_or_assign方法让我们无需像之前一样额外编写先判断是否存在不存在则插入存在则更新的代码了。
废话不多说看简单的demo实例代码
#include stdafx.h
#include iostream
#include mapusing namespace std;void PrintMap(const string type, const mapstring, int val)
{cout type endl;for (const auto [user, age] : val){cout user : age endl;}
}int main()
{mapstring, int map_user_age { {Tom, 10}, {Jerry, 12}, {Neo, 13} };PrintMap(original map, map_user_age);auto [iter_tom, inserted_tom] map_user_age.try_emplace(Tom, 14);PrintMap(insert Tom:14(try_emplace), map_user_age);auto [iter_jim, inserted_jim] map_user_age.try_emplace(Jim, 14);PrintMap(insert Jim:14(try_emplace), map_user_age);auto [iter_neo, inserted_neo] map_user_age.insert_or_assign(Neo, 18);PrintMap(insert Neo:18(insert_or_assign), map_user_age);auto [iter_tom_ia, inserted_tom_ia] map_user_age.insert_or_assign(Tom, 16);PrintMap(insert Tom:16(insert_or_assign), map_user_age);return 0;
}
猜一猜运行结果 上述实例代码可以看到insert_or_assign方法与 try_emplace的不同之处在于如果对应的key已经存在使用insert_or_assign会将新的value值赋值给已经存在的key(建立新的键值对映射)。