向量迭代器提供错误的值 [英] Vector iterator providing wrong value
问题描述
我的Graph实现面临问题,特别是函数printGraph()
.该函数包含一个循环,用于打印图形的邻接表表示形式.如果我使用成员对象变量adj
循环,那么它将向我显示正确的输出为:
I'm facing issue with my Graph implementation, specifically the function printGraph()
. This function contains a loop to print the adjacency list representation of the graph. If I loop though using the member object variable adj
then it shows me the correct output which is:
0 : 1 2 2
1 : 0 2
2 : 0 1 0 3
3 : 2 3 3
但是,如果我使用吸气剂方法adjL()
,那么它将为我提供错误的输出,即:
However, If I use the getter method adjL()
then it provides me a wrong output which is:
0 : 0 0 2
1 : 0 0
2 : 0 0 0 3
3 : 0 0 3
我很可能犯了一个愚蠢的错误,但我似乎无法抓住它.任何帮助表示赞赏.我想我无法理解如何使用getter方法adjL()
返回的值.
Most likely I am making a stupid mistake but I can't seem to catch it. Any help is appreciated. I think I am not able to understand how to use the value returned by the getter method adjL()
.
class UndirectedGraph {
//vector<vector <int> > adj;
public:
vector<vector <int> > adj;
UndirectedGraph(int vCount); /* Constructor */
void addEdge(int v, int w); /* Add an edge in the graph */
vector<int> adjL(const int v) const ; /* Return a vector of vertices adjacent to vertex @v */
void printGraph();
};
UndirectedGraph::UndirectedGraph(int vCount): adj(vCount) {
}
void UndirectedGraph::addEdge(int v, int w) {
adj[v].push_back(w);
adj[w].push_back(v);
edgeCount++;
}
vector<int> UndirectedGraph::adjL(const int v) const {
return adj[v];
//return *(adj.begin() + v);
}
void UndirectedGraph::printGraph() {
int count = 0;
for(vector<vector <int> >::iterator iter = adj.begin(); iter != adj.end(); ++iter) {
cout << count << " : ";
/*
for(vector<int>::iterator it = adj[count].begin(); it != adj[count].end(); ++it) {
cout << *it << " ";
}
*/
for(vector<int>::iterator it = adjL(count).begin(); it != adjL(count).end(); ++it) {
cout << *it << " ";
}
++count;
cout << endl;
}
}
int main() {
UndirectedGraph g(4);
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 2);
g.addEdge(2, 0);
g.addEdge(2, 3);
g.addEdge(3, 3);
g.printGraph();
}
推荐答案
由于adjL
奇怪地返回值,因此以下行被破坏了:
Since adjL
curiously returns by value, the following line is broken:
for(vector<int>::iterator it = adjL(count).begin(); it != adjL(count).end(); ++it) {
您要比较两个不同容器(和)中的迭代器,并将迭代器存储到立即超出范围的临时变量中,而在没有引起海森堡的情况下,无法立即读取其值可能会转过他的坟墓.
You're comparing iterators from two different containers, and you're storing an iterator to a temporary that immediately goes out of scope, its value(s) immediately becoming impossible to read without causing Heisenberg to possibly turn in his grave.
adjL
应该返回const vector<int>&
.
这篇关于向量迭代器提供错误的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!