向量迭代器提供错误的值

Nar*_*aki 2 c++ pointers iterator graph vector

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

0 : 1 2 2 
1 : 0 2 
2 : 0 1 0 3 
3 : 2 3 3 
Run Code Online (Sandbox Code Playgroud)

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

0 : 0 0 2 
1 : 0 0 
2 : 0 0 0 3 
3 : 0 0 3 
Run Code Online (Sandbox Code Playgroud)

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

Lig*_*ica 9

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

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

您正在比较来自两个不同容器的迭代器,并且您将迭代器存储到一个立即超出范围的临时值,它的值立即变得无法读取而不会导致海森堡可能在他的坟墓中转入.

adjL应该返回一个const vector<int>&.

  • 值得注意的是,如果你在VS2013中构建并运行它,它断言"`Expression:vector iterators incompatible`"它会告诉你发生了什么. (2认同)