gpt4 book ai didi

c++ - STL map Custom Key Class [默认构造函数]

转载 作者:行者123 更新时间:2023-11-28 06:28:59 24 4
gpt4 key购买 nike

我有一个带有如下 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 <--> 2 添加到图中。任何帮助将不胜感激。

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

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

最佳答案

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

你的 Node::operator<比较futureVol ,除了默认值 1.0 之外,您永远不会将其设置为任何其他值, 所以你的程序创建的所有节点都是等价的,直到 std::map<Node, ...>被关注到。因此,edges map 只有一个条目。当你写作时

edges[nodes[n1]].push_back(nodes[n2]);
edges[nodes[n2]].push_back(nodes[n1]);

两个语句都更新同一个条目。

关于c++ - STL map Custom Key Class [默认构造函数],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27990191/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com