STL 映射 - 插入或更新
我有一个对象映射,我想更新映射到键的对象,或者创建一个新对象并插入到映射中。更新是通过另一个函数完成的,该函数采用指向对象的指针 (void update(MyClass *obj))
在映射中“插入或更新”元素的最佳方法是什么?
I have a map of objects and I want to update the object mapped to a key, or create a new object and insert into the map. The update is done by a different function that takes a pointer to the object (void update(MyClass *obj))
What is the best way to "insert or update" an element in a map?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
operator[]
The
operator[]
使用类似以下代码片段的内容:
如果您想测量可能提高性能的内容,您可能需要使用
.lower_bound()
来查找条目的位置,并将其用作在以下情况下插入的提示:您需要插入一个新对象。With something like the following snippet:
If you want to measure something that might improve performance you might want to use
.lower_bound()
to find where an entry and use that as a hint to insert in the case where you need to insert a new object.类似于:
这里有一个很好的参考链接
something like:
here a nice reference link
operator[]
已经完成了您想要的操作。有关详细信息,请参阅参考。The
operator[]
already does, what you want. See the reference for details.insert 的返回值是“一对由插入元素(或阻止插入的元素)的迭代器和表示插入是否发生的布尔值组成的对”。
因此你可以简单地做
注:
由于您的问题涉及原始指针,并且您说您希望 Update 函数采用指针,因此我在代码片段中做出了这一假设。假设 CreateFunction() 返回一个指针,而 UpdateFunction() 需要一个指针。
不过,我强烈建议不要使用原始指针。
The return value of insert is "a pair consisting of an iterator to the inserted element (or to the element that prevented the insertion) and a bool denoting whether the insertion took place."
Therefore you can simply do
NOTE:
Since your question involved raw pointers, and you said you wanted your Update function to take a pointer, I have made that assumption in my snippet. Assume that CreateFunction() returns a pointer and UpdateFunction() expects a pointer.
I'd strongly advise against using raw pointers though.
在 C++17 中,函数insert_or_assign 如果不存在则插入,如果存在则更新。
In C++17, function insert_or_assign insert if not existing and update if there.