【发布时间】:2016-09-18 14:37:57
【问题描述】:
我正在尝试访问节点结构中的边_,因此我可以执行一个 for 循环来将边复制到我的复制构造函数的新图形对象中。
当我尝试访问节点中的边_时,我遇到了以下错误,这让我很困惑。
tests/Graph.tem:280:24: error: ‘struct std::pair<const std::__cxx11::basic_string<char>, std::shared_ptr<gdwg::Graph<std::__cxx11::basic_string<char>, int>::Node> >’ has no member named ‘edges_’
for (auto edge: node.edges_) {
~~~~~^~~~~~
我正在尝试做一个复制构造函数,将图中的节点和边深度复制到一个新的图对象:
template <typename N, typename E>
Graph<N, E>::Graph(const Graph &g):
nodes_{g.nodes_}
{
for (auto node: g.nodes_) {
for (auto edge: node.edges_) {
}
}
}
以下是我的 Graph 类:
template <typename N, typename E> class Graph {
private:
struct Node;
struct Edge;
struct Node {
N val_;
int numEdges_;
int numIncomingEdges_;
std::set<std::shared_ptr<Edge>> edges_;
std::set<std::shared_ptr<Edge>> incomingEdges_;
Node() {}
Node(const N x) : val_{x} { numEdges_=0; numIncomingEdges_=0; }
void printNode(N n);
~Node();
void update();
};
struct Edge {
std::weak_ptr<Node> orig;
std::weak_ptr<Node> dest;
E val_;
Edge(std::shared_ptr<Node> o, std::shared_ptr<Node> d, E x);
Edge() {};
void printEdge();
~Edge();
};
首先,我如何访问它来进行深拷贝?似乎有一些ptr问题。其次,有没有一种简单的方法可以将存储在节点内的边进行深度复制?
【问题讨论】:
-
Graph::nodes_的类型是什么?如果它是std::map<std::string, std::shared_ptr<Node>>,如您的错误消息所示,node的类型为std::pair<std::string, std::shared_ptr<Node>>,因此您应该使用node.edges_而不是node.edges_。 -
std::map > nodes_;
-
所以对于第一个问题,您应该将
for (auto edge: node.edges_)替换为for (auto edge: node.second->edges_)。 -
哦,是的,它正在工作!第二个呢?
-
第二个问题更复杂:你需要在你的构造函数内部有一个本地关联映射来存储
g的节点和你的副本的节点之间的连接。
标签: c++ shared-ptr copy-constructor deep-copy directed-graph