将自定义类作为键的Unordered_map

时间:2018-04-12 23:03:53

标签: c++ c++11 unordered-map

我的问题是如何使用自定义类作为键。我找到了一些我需要做的链接,例如在我的类上创建自定义哈希函数,以及更改()和==(我相信)。问题是我无法对这些线程发表评论,我对如何在.h文件中实现这3个内容感到迷茫。 C++ unordered_map using a custom class type as the key 这个网站只是总结了问题,但我不知道如何或在哪里把我的信息定制到我的代码。感谢任何帮助,谢谢。

编辑: 我的班级代码:

class apples{
public:
    apples(){
        removed = false;
        hasPortal = false;
        distance = 9999;
        from.first = -1;
        from.second = -1;
        location.first=-1;
        location.second=-1;
        portal.first = -1;
        portal.second = -1;
    }
    bool removed,hasPortal;
    int distance;
    pair<int,int> from;
    pair<int, int> location;
    pair<int,int> portal;
    int portalDistance;
};

然后我为Dijkstra的

设置了minPriorityQueue
//Dijkstra's Algorithm
//1. Put all nodes (apples) into the queue with high distance all except the begining apple
//2. pop out and update all distances from distance + distanace to neighboring apple
//3. continuously pop out and update the neighboring apples of the popped apple
MinPriorityQueue<apples> tree;
for(int i=0; i<m.size(); i++){
    for(int j=0; j<m[i].size(); j++){
        if(!fruits[i][j].removed){
            tree.push(fruits[i][j], fruits[i][j].distance);
        }
    }
}

我的minPriorityQueue:

#include <unordered_map>
#include <vector>
#include <utility> // Has pair and swap

using namespace std;

template <typename T>
class MinPriorityQueue
{
public:
//Here there is push, pop, decrease_key, and front
//They all work as was tested somewhere else
private:
    unordered_map<T, int> I; // Maps elements to indices in H.
    vector< pair<T, int> > H;     // The array containing the heap.
};

因此,在尝试将自定义类用作键时会出现问题。我只是模糊地理解链接中另一个问题的答案。我想我要求澄清并且只是理解这些东西应该去哪里以及如何编写代码。

0 个答案:

没有答案