[英]Comparison of two class instances not having members as unique identifiers
考虑两个类, Node
和Edge
,分别代表多重图的节点和边(请参阅下面的 MWE 代码)。 我的意图是使用三个unordered_map
:
(a) 从Node
变量到Edge
数据,
(b) 从Edge
变量到Node
数据,以及
(c) 从Node
对到double
变量。
我尝试为Node*
和Edge*
编写bool operator==()
函数,为Node*
、 Edge*
和pair<Node*,Node*>
编写哈希函数。
我的第一个问题与Edge
的bool operator==()
函数有关。 尽管Node
s 的标签肯定是唯一的,但是对于具有相同start
s 和end
s() 的多条边,这个bool operator==()
函数是不正确的。 是否有机会使用例如Edge
的内存地址构造正确的bool operator==()
函数?
第二个问题是Node/Edge/pair<Node,Node>
如果只假设简单的边Node/Edge/pair<Node,Node>
这些函数是否会导致只保存不同的Node/Edge/pair<Node,Node>
对象。
所以,我的 MWE 如下:
#include<string>
#include<vector>
#include<utility>
#include<unordered_map>
#include<iostream>
#include <bits/stdc++.h>
using namespace std;
class Node
{
public:
Node(){};
string label;
bool operator==(const Node* other) const
{return label == other->label;};
};
class Edge
{
public:
Edge(){};
Node *start, *end;
double weight;
bool operator==(const Edge* other) const
{return start->label == other->start->label &&
end->label == other->end->label;};
//{return this == *other;}
};
namespace std
{
template <>
struct hash<Node*>
{
size_t operator()(const Node* node) const
{return hash<string>()(node->label);}
};
template <>
struct hash<Edge*>
{
size_t operator()(const Edge* edge) const
{
auto hash1 = hash<Node*>()(edge->start);
auto hash2 = hash<Node*>()(edge->end);
return hash1 ^ hash2;
}
};
template <>
struct hash<pair<Node*,Node*>>
{
size_t operator()(const pair<Node*, Node*>& p) const
{
auto hash1 = hash<Node*>()(p.first);
auto hash2 = hash<Node*>()(p.second);
return hash1 ^ hash2;
}
};
};
int main()
{
Edge* edge;
Node* node;
unordered_map<Node*,Edge> n2e;
unordered_map<Edge*,Node> e2n;
unordered_map<pair<Node*,Node*>,double> np2w;
edge = new Edge();
edge->weight = 1.0;
edge->start = new Node();
edge->start->label = "A";
edge->end = new Node();
edge->end->label = "B";
n2e[edge->start] = *edge;
e2n[edge] = *(edge->start);
np2w[make_pair(edge->start, edge->end)] = edge->weight;
edge = &n2e[edge->start];
node = &e2n[edge];
return 0;
}
您主要定义operator==(const Edge&, const Edge*)
,
而您需要operator==(const Edge*, const Edge*)
,但不能定义后者。
您必须编写定义operator()(const Edge*, const Edge*) const
,并在std::unordered_map
提供它。
struct MyEdgeComp
{
bool operator()(const Edge* lhs, const Edge* rhs) const {
return *lhs == *rhs; // Assuming you implement it
}
};
std::unordered_map<Edge*, Node, std::hash<Edge*>, MyEdgeComp> e2n;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.