我遇到了一个奇怪的问题,我无法弄清其原因。我所做的基本上如下:首先,将顶点和图形定义为
class Vertex {
public:
int value;
std::vector<std::shared_ptr<Vertex>> adjVertex;
Vertex(int v):value(v){};
};
class Graph {
void addEdge(std::shared_ptr<Vertex> & v1, std::shared_ptr<Vertex> & v2) {
std::cout << "v1: " << v1->value << "v2:" << v2->value << std::endl;
if (mVMap.find(v1) == mVMap.end()) {
// not found
mV.push_back(v1);
mVMap[v1] = --mV.end();
v1->adjVertex.push_back(v2);
} else {
// in the map
auto it = mVMap[v1];
(*it)->adjVertex.push_back(v2);
}
if (mVMap.find(v2) == mVMap.end()) {
mV.push_back(v2);
mVMap[v2] = --mV.end();
}
// why here mVMap[v1] becomes null_ptr
}
private:
std::vector<std::shared_ptr<Vertex>> mV;
std::unordered_map<std::shared_ptr<Vertex>, std::vector<std::shared_ptr<Vertex>>::iterator> mVMap;
};
但是,在使用时
auto v1 = std::make_shared<Vertex>(1);
auto v2 = std::make_shared<Vertex>(2);
Graph testGraph;
testGraph.addEdge(v1, v2);
addEdge
的末尾,为什么这里mVMap [v1]变为null_ptr?