在ptr_map中插入或更新 [英] insert or update in ptr_map

查看:65
本文介绍了在ptr_map中插入或更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果存在键,则ptr_map的insert方法不会更新数据.因此,我们需要使用replace:

The insert method of ptr_map does not update data if a key exists. So we need to use replace:

提升ptr_map替换值

ptr_map是否具有insertOrUpdate的方法?

Does ptr_map have a way of insertOrUpdate?

1) if a key does not exist, calls insert
2) if it exists, call replace

我想这就是std :: map插入的工作方式.

I guess this is how std::map insert works.

ptr_map具有[]运算符.但这返回参考吗?我不确定使用它进行上述操作是否安全.

ptr_map has a [] operator. But it returns reference? I am not sure if it is safe to use it for doing the above.

谢谢

推荐答案

我想这就是std :: map插入的工作方式

I guess this is how std::map insert works

不.实际上,std::map::insert查找匹配的键,并将迭代器返回到现有元素(如果找到).它不会替换. (您可能对operator[]感到困惑,它会返回对新元素/现有元素的左值引用).

No. In fact, std::map::insert looks up a matching key and returns the iterator to the existing element, if found. It does not replace. (You maybe confused with operator[] which returns a lvalue reference to a new/existing element).

ptr_map具有[]运算符.但这返回参考吗?我不确定使用它进行上述操作是否安全.

ptr_map has a [] operator. But it returns reference? I am not sure if it is safe to use it for doing the above.

当然可以.但是,如果您的元素类型是多态的,则应该分配给参考. (可以说,多态值类型是Boost Pointer容器的关键用例).因为如果这样做,您可能会得到 Object Slicing (什么是对象切片? ).

Of course you can. However, you should not assign to the reference if your element type is polymorphic. (Arguably, polymorphic value types are a key use case for Boost Pointer Containers). Because if you do you might end up with Object Slicing (What is object slicing?).

如果您确实要用/another object/替换对象(托管指针),请使用ptr_map::replace.如果您只需要更新地图中已经存在的对象,请随时使用operator[].

If you truly want to replace the object (managed pointer) with /another object/ use ptr_map::replace. If you need to just update the object that is already in the map, feel free to use operator[].

这篇关于在ptr_map中插入或更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆