我如何知道std :: map插入成功或失败? [英] How do I know if std::map insert succeeded or failed?

查看:1135
本文介绍了我如何知道std :: map插入成功或失败?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在多线程应用程序中有一个映射,将名为uuid的类映射到指针。
我想知道插入操作是否成功失败。

I have a map in a multithreaded app mapping a class called uuid to pointer. What I want to know if an insert operation succeeded for failed.

例如

_mymap.insert(hint, MyMap::value_type(entry.uuid, itemptr));

如果失败,它会抛出异常吗?

Does it throw an exception or something if it fails?

推荐答案

事实上,使用hint参数的insert方法不会返回插入成功与否。检查插入是否实际发生的一种方法是在插入之前和之后检查映射的大小。如果它是相同的,则插入失败(即密钥已经存在)。我知道这听起来很丑陋,但这是我能想出的最有效的方式。事实上,我相信没有令人信服的理由,带有提示的插入不应该像普通非提示插入一样返回一对(包括bool)。但是一旦它在一个旧的标准中被指定,它是很难改变,因为它是一个突破性的变化,C ++社区大多反对。

In fact the insert method which takes a hint parameter does not return whether the insert succeeded or not. One way to check if insert actually happened would be to check the size of the map before and after insertion. If it is the same, then insert has failed (i.e. the key was already present). I know it sounds ugly, but that's the most efficient way I could come up with. In fact I believe that there is no compelling reason that the insert with a hint should not return a pair (including the bool) just like the regular non-hint insert does. But once it has been specified in an older standard, it is very hard to change, since it is a breaking change, which the C++ community mostly resents.

查看此链接

...返回一个对,其成员 pair :: first 设置为迭代器指向新插入的元素或在地图中已经具有相同值的元素。如果插入新元素,则对中的 pair :: second 元素设置为true。如果存在相同值的元素,则设置为false。

... returns a pair, with its member pair::first set to an iterator pointing to either the newly inserted element or to the element that already had its same value in the map. The pair::second element in the pair is set to true if a new element was inserted or false if an element with the same value existed.

链接还包含一个示例

例如:

if(mp.insert(make_pair(key, value)).second == false)
{
   cout << "Insertion failed. Key was present"
}

这篇关于我如何知道std :: map插入成功或失败?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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