c++ - vector 迭代器与 const vector& 不兼容

标签 c++

我正在编写图表程序。在这个程序中,我有一个方法,它必须返回源自顶点的弱组件内的顶点。我收到:错误“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被视为 const在你的函数内。 beginconst vector<T>上返回 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);
    }
}

关于c++ - vector 迭代器与 const vector& 不兼容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36167480/

相关文章:

c++ - 如何退出(转到父循环的下一个元素)for 循环内的 for 循环

c++ - 如何在 C++ 中正确执行线程?

C++ - 不跳出循环

c++ - 无法将 boost::lambda::... 转换为 long long unsigned int

c++ - 如何销毁单例实例,或者为什么以下代码适用于析构函数?

c++ - 有条件地跳过 dll 依赖项

c++ - 如何确定 lightuserdata 的类型?

c++ - 符号文件和调试

c++ - 有没有办法为任何函数编写通用代码,使其可以(异步地)执行并从线程池获得返回值?

c++ - 开始在 Visual Studio 2013 中使用 clang 3.6.0;如何解决我的 "unknown argument: -ftemplate-depth"编译器错误?