Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/mercurial/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 插入不';t从哈希函数中检索密钥_C++_Dictionary_Hash_Hashmap_Unordered Map - Fatal编程技术网

C++ 插入不';t从哈希函数中检索密钥

C++ 插入不';t从哈希函数中检索密钥,c++,dictionary,hash,hashmap,unordered-map,C++,Dictionary,Hash,Hashmap,Unordered Map,我试图使用哈希函数将结构存储到映射中。当创建两个相同的对象时,我确实从哈希函数中获得了一个相同的键,但是每个元素仍然插入到映射中 这是我的密码: // Key struct GridrecordKey { // Keys double key1; double key2; ... GridrecordKey() { key1 = 0; key2 = 0; ... } bool operat

我试图使用哈希函数将结构存储到映射中。当创建两个相同的对象时,我确实从哈希函数中获得了一个相同的键,但是每个元素仍然插入到映射中

这是我的密码:

// 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 }); 
    }
intmain(){
GridrecordKey;//该键
gridrecord;//记录
无序的_映射;//映射
//修改键并将记录插入地图
key.key1=1;
插入({key,record});
//保留相同的键,并尝试在映射中插入另一条记录
key.key1=1;
//在这里,记录被添加到地图中,而它不应该这样做
//密钥已存在
auto x=map.insert({key,record});
}

提前谢谢

我编译了您的代码,并在插入两次相同元素后打印了地图中的元素计数:

std::cout << map.size() << std::endl;
--> 1

std::cout问题是由一个关键变量引起的。其类型为char[],比较函数无法正常工作。使用strcmp()修复了该问题。

谢谢大家!

每个元素仍然插入是什么意思?该行应该执行,尽管有重复的键。我的意思是,映射中添加了两条记录,而应该只有一条记录,因为键是相同的。为什么说这两条记录都添加了?请参阅下面的答案,了解一些上下文。我的结构实际上更复杂(也包括指针)。也许问题就出在这里