确定元素是否已插入到哈希映射中
Determining if an element was inserted into a hash map
我正在使用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 = ...;
相关文章:
- 删除一个线程上有数百万个字符串的大型哈希映射会影响另一个线程的性能
- 使用 Key 对 C++ 中的哈希映射进行排序. 无法排序
- 哈希映射使用 nullptr c++ 初始化节点的动态数组
- 如何按值对无序哈希映射进行排序
- 哈希映射如何在 c++ 中实现?
- C++中的哈希映射等效
- 以字符串向量作为值的哈希映射
- 来自并发哈希映射的迭代器是否安全
- 如何在这个哈希映射中实现 AVL 树
- 无法迭代结构"string"的哈希映射:[列表] C++
- 什么是最快的解决方案,用于读/写入哈希映射
- 可以安全地依赖unordered_map中的初始化值(哈希映射)
- 使用按插入方式排序的参数创建哈希映射
- 哈希映射没有可行的重载 '='
- 使用分配器对哈希映射进行高效的序列化和反序列化
- 由于动态数组而导致的哈希映射内存泄漏
- 为boost哈希映射定义自定义哈希函数
- 是我们迭代时更改哈希映射的行为,已定义
- 哈希映射和有序遍历
- 哈希映射错误:与调用 '(const __gnu_cxx::.