STL映射自定义键类[默认构造函数]

时间:2015-01-16 18:12:48

标签: c++ graph stl stdmap

我有一个带有Node类的图表实现,如下所示

class Node {
public:
    Node() : idx(0), volume(1.0), futureVol(1.0), isCoarse(false) { }
    Node(index n) : idx(n), volume(1.0), futureVol(1.0), isCoarse(false) { }
    Node(const Node& a) : idx(a.idx), volume(a.volume), futureVol(a.futureVol), isCoarse(a.isCoarse) { }

    ...

    bool operator<(const Node& n) const {
        return futureVol > n.futureVol;
    }
    bool operator==(const Node& n) const {
        return idx > n.idx;
    }

    Node& operator=(const Node& node){
        if(this != &node){
            futureVol = node.futureVol;
            volume = node.volume;
            isCoarse = node.isCoarse;
            idx = node.idx;
        }
        return *this;
    }

private:
    index idx;
    double volume;
    double futureVol;
    bool isCoarse;
};

以及具有以下实施的图表:

class Graph{
private:
    std::map<Node,std::vector<Node>> edges;
    std::map<index, std::map<index, edgeweight>> edgeWeights;
    std::map<index, Node> nodes;
    Graph(const Graph& g);
    Graph& operator=(const Graph& g);
    count numNodes;
public:
    Graph(count& n); //default
    ~Graph(); //destructor
    Graph(std::vector<Node>&);
    void print();
    const std::vector<Node> neighbors(const index& idx) const;
    const std::vector<Node> coarseNeighbors(const index& idx) const;
    void addEdge(index &node1, index &node2, edgeweight& weight);
    void addEdges(std::map<index, std::map<index, edgeweight> >& e );
    edgeweight weight(const index& idx, const index& idx2) const;
    edgeweight weightedDegree(const index& idx) const;
    count degree(const index& idx) const;
    std::map<index, Node>& getNodes(){return nodes;}
    const count getSize() const { return numNodes; }
};

#endif

和Graph.cpp:

#include "graph.h"
#include <algorithm>

Graph::Graph(count& n): 
edges(),
edgeWeights(),
nodes(),
numNodes(n)
{
    for(index i=0; i<numNodes;i++){
        Node n(i);
        nodes[i] = n;   
    }
}
...
void Graph::addEdge(index& n1, index& n2, edgeweight& weight){

    edgeWeights[n1][n2]= weight;
    edgeWeights[n2][n1]= weight;
    edges[nodes[n1]].push_back(nodes[n2]);
    edges[nodes[n2]].push_back(nodes[n1]);
}
...

问题是每当我添加新边缘时。调用Node的默认构造函数,我最终得到0作为节点Id而不是传递给addEdge的原始节点,例如addEdge(1,2,4.0)将添加边0&lt; - &gt; 2到图表。任何帮助将不胜感激。

我尝试编写如下所示的自定义哈希函数,但它没有帮助:

namespace std
{
    template <>
    struct hash<Node>
    {
        size_t operator()(const Node& n) const
        {
            return (hash<float>()(n._index()) >> 1);
        }
    };
}

1 个答案:

答案 0 :(得分:1)

回想一下std::map使用operator<,而不是operator==。它认为两个密钥等同于!(key1 < key2) && !(key2 < key1)

您的Node::operator<比较futureVol,您永远不会将其设置为默认值1.0以外的任何值,因此您的程序创建的所有节点都相同,只要{ {1}}令人担忧。因此,std::map<Node, ...>地图只有一个条目。当你写

edges

两个语句都会更新相同的条目。

相关问题