【问题标题】:Vector iterator providing wrong value提供错误值的向量迭代器
【发布时间】:2015-02-20 11:24:45
【问题描述】:

我的 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();
}

【问题讨论】:

    标签: c++ pointers vector graph iterator


    【解决方案1】:

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

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

    您正在比较来自两个不同容器的迭代器,并且您正在将迭代器存储到立即超出范围的临时对象中,其值立即变得无法读取而不会导致 Heisenberg可能会在他的坟墓里上交。

    adjL 应该返回一个const vector&lt;int&gt;&amp;

    【讨论】:

    • 值得注意的是,如果你在 VS2013 中构建并运行它,它会断言“Expression: vector iterators incompatible”会告诉你发生了什么。
    猜你喜欢
    • 2020-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-18
    • 1970-01-01
    • 2017-03-07
    • 2017-12-29
    相关资源
    最近更新 更多