插入不从哈希函数中检索键
insert doesn't retrieve key from hash function
我正在尝试使用键的哈希函数将结构存储到映射中。创建两个相同的对象时,我确实从哈希函数中获得了相同的键,但是每个元素仍然插入到映射中。
这是我的代码:
// Key
struct GridrecordKey {
// Keys
double key1;
double key2;
...
GridrecordKey() {
key1 = 0;
key2 = 0;
...
}
bool operator==(const GridrecordKey &other) const {
return (key1 == other.key1
&& key2 == other.key2);
}
};
// Hash function
struct GridrecordKeyHasher
{
std::size_t operator()(const GridrecordKey& k) const
{
using boost::hash_value;
using boost::hash_combine;
// Start with a hash value of 0 .
std::size_t seed = 0;
hash_combine(seed, hash_value(k.key1));
hash_combine(seed, hash_value(k.key2));
// Return the result.
return seed;
}
};
// Record
struct gridrecord {
double element1;
double element2;
...
};
我的主程序示例:
int main() {
GridrecordKey key; // The key
gridrecord record; // The record
unordered_map<GridrecordKey, gridrecord, GridrecordKeyHasher> map; // The map
// Modify the key and insert record into map
key.key1 = 1;
map.insert({ key, record });
// Keep the same key and try to insert another record into the map
key.key1 = 1;
// Here the record is added to the map while it should't as this
// key already exist
auto x = map.insert({ key, record });
}
提前感谢!
在您插入两次相同的元素后,我编译了您的代码并打印了地图中的元素计数:
std::cout << map.size() << std::endl;
--> 1
因此,您的代码正在按预期/想要的方式运行。
你怎么会认为它入了 2 次?
问题是由一个关键变量引起的。它的类型是 char[],比较函数无法正常工作。使用 strcmp(( 解决了这个问题。谢谢!
相关文章:
- 如何检索指向在单独线程上运行的函数的移动指针?
- std::shared_ptr 使用别名构造函数,是否可以检索初始指针值?
- 有什么方法可以从不同函数的变量中检索值吗?c++
- Getter 函数,用于在 2d 数组是类的数据成员时检索 2d 数组元素
- 用于检索当前正在使用的应用程序的函数
- 如何在函数中检索指针结构
- 插入不从哈希函数中检索键
- 我如何从循环内部使用迭代器的函数内部的getter中检索特定的成员
- 如何在没有辅助函数模板的情况下检索可变参数模板参数
- 使用 getter 函数时,C++ 无法检索正确的值
- 通过空隙函数检索所有数据
- 从GCC功能树节点中检索函数参数
- 是否可以检索 C++11 中线程函数的返回值
- 从未知dll(c++)中检索函数(名称、返回类型、参数)
- 如何从另一个过程的Callstack地址检索函数名称
- 用于在C++代码库中检索函数和方法列表的工具
- 从容器中检索函数指针
- 数组列表和使用插入和检索函数的问题(段核心转储)
- Boost协程如何在coro_t完成后检索函数返回值
- 检索函数调用图