矢量迭代器与 const Vector&不兼容



我正在为图形编写程序。在这个程序中,我有一个方法,它必须返回源自顶点的弱组件内的顶点。我得到:错误"矢量迭代器不兼容"

struct graph {
    std::vector <std::vector<int>> gr;
};

std::vector<int> weak_component(const graph& g, int vertex) {
    std::vector<int> ret;
    stack<int> s;
    s.push(vertex);
    vector<int>::iterator j;
    bool* used = new bool[g.gr.size()];
    while (!s.empty()) {
        int hodn=s.top();
        s.pop();
        used[hodn] = true;
        for (j == g.gr[hodn].begin(); j != g.gr[hodn].end(); j++) {
            if (!used[*j]) {
                s.push(*j);
                ret.push_back(*j);
        }
    }
}
    return ret;
}

怎么了?

由于您将g作为const graph&,这意味着g.gr被视为函数内部的constconst vector<T>上的begin返回const_iterator。 (您也使用==而不是=进行分配(

for (std::vector<int>::const_iterator j = g.gr[hodn].begin(); ...)

但是对于 C++11 或更高版本,您也可以使用 auto 来避免这种情况

for (auto j = g.gr[hodn].begin(); ...)

或基于范围:

for (auto&& e : g.gr) {
    if (!used[e]) {
        s.push(e);
        ret.push_back(e);
    }
}

最新更新