向量迭代器提供错误的值

时间:2015-02-20 11:24:46

标签: c++ pointers vector graph iterator

我的Graph实现面临问题,特别是函数printGraph()。此函数包含一个循环,用于打印图形的邻接列表表示。如果我使用成员对象变量adj循环,那么它会显示正确的输出:

0 : 1 2 2 
1 : 0 2 
2 : 0 1 0 3 
3 : 2 3 3 

但是,如果我使用getter方法adjL(),那么它会给我一个错误的输出:

0 : 0 0 2 
1 : 0 0 
2 : 0 0 0 3 
3 : 0 0 3 

我很可能犯了一个愚蠢的错误,但我似乎无法抓住它。任何帮助表示赞赏。我想我无法理解如何使用getter方法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();
}

1 个答案:

答案 0 :(得分:7)

由于adjL奇怪地按值返回,因此以下行被破坏:

for(vector<int>::iterator it = adjL(count).begin(); it != adjL(count).end(); ++it) {

您正在比较来自两个不同容器的迭代器,您将迭代器存储到一个立即超出范围的临时值,其值立即变为不可能读书时没有让海森堡可能转入他的坟墓。

adjL应返回const vector<int>&