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