我尝试更新dist
课程中的变量Vertex
。 Vertex
对象保留在unordered_map
类Graph
(vertices
)的值中。
我遇到的问题是,当我尝试通过g.get_vertex(vert).set_distance(34)
修改dist变量时(此处g
是图形对象,而vert
是一个顶点名称,其值对在{{} 1}}保持其顶点对象)它无法进行任何更改。例如
如果我做
unordered_map
给出10000000而不是34(在默认构造函数中将10000000定义为dist值)。
g.get_vertex(vert).set_distance(34);
cout << g.get_vertex(vert).get_distance()
答案 0 :(得分:3)
get_vertex
按值返回,因此您可以有效地修改vertices
中元素的副本。通过引用返回以获得您期望的行为
Vertex& getVertex(int x)
get_vertices()
和get_connections()
的simiar。
答案 1 :(得分:1)
此代码存在许多问题。不完整的清单如下。
int vert_num
是不必要的,只需使用std::unordered_map<>::size()
您经常修改临时对象,例如
void add_edge(int x, int y , int dist){
if (vertices.find(x) == vertices.end() ){
add_vertex(x);
}
if (vertices.find(y) == vertices.end() ){
add_vertex(y);
}
Vertex vert ; // automatic/temporary object
vert.add_neighbour(y, dist); // modify the object
Vertex vert2 ;
vert2.add_neighbour(x, dist);
// end of scope: temporaries are destroyed
}
最后4行中的代码什么都不做(并且可以优化掉)。你可能想要做的是
void add_edge(int x, int y , int dist){
vertices[x].add_neighbour(y, dist);
vertices[y].add_neighbour(x, dist);
}
(请注意,unordered_map<>::operator[]
如果找到给定的密钥,则会插入新元素。
您在
中返回副本Vertex get_vertex(int x){
return vertices[x];
}
unordered_map<int,Vertex> get_vertices(){
return vertices;
}
代码中的修改,如
g.get_vertex(vert).set_distance(34);
对Vertex
中存储的实际Graph
没有影响。相反,你应该
Vertex&get_vertex(int x){
return vertices[x];
}
Vertex const&get_vertex(int x) const {
auto find=vertices.find(x);
if(find==vertices.end())
throw std::runtime_error("unknown vertex requested");
return find->second;
}
unordered_map<int,Vertex>&get_vertices(){
return vertices;
}
unordered_map<int,Vertex> const&get_vertices() const{
return vertices;
}
虽然可以说你不应该公开vertices
地图(任何需要由class Graph
处理的功能)。
答案 2 :(得分:0)
此函数返回从集合
复制的新Vertex
实例
Vertex get_vertex(int x)
{
return vertices[x];
}
临时对象死亡时,这些更改会丢失。