我正在尝试使用键的哈希函数将Struct存储到地图中。在创建两个相同的对象时,我从哈希函数中获得了相同的键,但每个元素仍然插入到地图中。
以下是我的代码:
// 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 });
}
提前致谢!
答案 0 :(得分:0)
在您插入两次相同元素后,我编译了您的代码并打印了地图中元素的数量:
std::cout << map.size() << std::endl;
--> 1
因此,您的代码按预期/需要运行。
你如何达到你认为插入2次的程度?
答案 1 :(得分:0)
问题是由于一个关键变量。它的类型是char [],比较函数无法正常工作。使用strcmp()修复了问题。 谢谢!