确定元素是否已插入到哈希映射中

Determining if an element was inserted into a hash map

本文关键字:哈希 映射 插入 元素 是否      更新时间:2023-10-16

我正在使用Google的稀疏哈希图,并试图确定是否插入或查找了值。以下有效,但显然它查找了两次。如何在没有双重查找的情况下做到这一点?

Element newElement = Element();
bool  inserted = ((*map).insert(pair<const int64, Element>(key, newElement))).second;
Element element = (*(((*map).insert(pair<const int64, Element>(key, newElement))).first)).second;
if (inserted)
    puts("INSERTED");

我无法检查元素的内容(它是一个结构),因为我想区分找到的默认元素和插入的 newElement。我无法弄清楚如何将((*map).insert(pair<const int64, Element>(key, newElement)))分配给变量,因为它属于包含sparse_hash_map类私有类型的模板类型。

试试这个:

typedef sparse_hash_map<...>::iterator sh_iterator; //you already have this, haven't you?
std::pair<sh_iterator, bool> res = map->insert(std::make_pair(key, newElement));
if (res.second)
    puts("INSERTED");

如果出于某种原因您不喜欢 std::make_pair 函数,您应该考虑对类型的 typedef:

typedef pair<const int64, Element> map_pair;

无论如何,insert的返回类型是pair<iterator, bool>,而 AFAIK iterator 是该类的公共类型定义。

顺便说一句,我不明白你为什么要做第二个insert......到达插入的元素?也许您应该声明element作为参考。在我建议的代码中:

Element &element = res.first->second;

当然,如果您使用的是 C++11,您可以简单地执行以下操作:

auto res = ...;