我正在尝试创建一个通过向量运行的for循环,将某些东西推入队列,更新向量结构的所有适当元素,然后再循环直到向量为空。
我遇到的问题是,通过我的for循环运行的函数似乎没有更新我的向量元素,即使我知道它应该改变,我也得到相同的输出。
这是项目要点https://gist.github.com/sgodfrey321/6cffd85896432b2942aa的链接,它只是有很多填充物,我不得不手工输入很多东西,所以它有点混乱。
首先,我将向量传递给while循环中的函数
void queueNodes(vector<vertex>& list, queue<vertex>& q);
就是这样
int counter = 0;
while (counter < 11) {
queueNodes(nodes, q);
counter++;
}
while循环是为了确保我足够多次遍历向量。现在在函数中我检查结构的incomingEdges是否为0,如果是,我将它推入队列并更新隔壁的incomingEdges:
void queueNodes(vector<vertex>& nodes, queue<vertex>& q) {
for (auto i : nodes) {
cout << endl << i.vertexName << " ";
if (i.incomingEdges == 0) {
i.nextDoorTop->incomingEdges--;
i.nextDoorMiddle->incomingEdges--;
i.nextDoorBottom->incomingEdges--;
q.push(i);
cout << "foo";
} else {
cout << "bar";
}
}
现在我希望当我再次使用更新的向量函数时,我会看到输出的变化,因为更新隔壁的incomingEdges会导致一些触发我正在寻找的条件。我写的输出显示隔壁的incomingEdges实际上在减少但是我似乎无法在函数调用中使用更新的向量。
我需要以某种方式返回向量吗?我确信我错误地调用了这个函数,但是有没有人有任何想法?
谢谢你 编辑:忘记通过引用队列传递!
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
struct vertex {
char vertexName;
int incomingEdges;
vertex* nextDoorTop;
vertex* nextDoorMiddle;
vertex* nextDoorBottom;
};
void queueNodes(vector<vertex>& nodes);
int main() {
vertex s, A, G, D, B, H, E, C, I, F, t;
s.vertexName = 's';
s.incomingEdges = 0;
s.nextDoorTop = &A;
s.nextDoorMiddle = &D;
s.nextDoorBottom = &G;
A.vertexName = 'A';
A.incomingEdges = 2;
A.nextDoorTop = &B;
A.nextDoorMiddle = &E;
G.vertexName = 'G';
G.incomingEdges = 1;
G.nextDoorTop = &D;
G.nextDoorMiddle = &E;
G.nextDoorBottom = &H;
D.vertexName = 'D';
D.incomingEdges = 2;
D.nextDoorMiddle = &E;
B.vertexName = 'B';
B.incomingEdges = 1;
B.nextDoorTop = &C;
H.vertexName = 'H';
H.incomingEdges = 1;
H.nextDoorTop = &E;
H.nextDoorMiddle = &I;
E.vertexName = 'E';
E.incomingEdges = 4;
E.nextDoorTop = &C;
E.nextDoorMiddle = &F;
E.nextDoorBottom = &I;
C.vertexName = 'C';
C.incomingEdges = 3;
C.nextDoorMiddle = &t;
I.vertexName = 'I';
I.incomingEdges = 2;
I.nextDoorTop = &F;
I.nextDoorMiddle = &t;
F.vertexName = 'F';
F.incomingEdges = 2;
F.nextDoorMiddle = &t;
t.vertexName = 't';
t.incomingEdges = 3;
vector<vertex> nodes { s, A, G, D, B, H, E, C, I, F, t };
cout << "Vertex Name: " << " Number Of Edges: " << endl;
for (auto i : nodes) {
cout << i.vertexName << " " << i.incomingEdges << " "
<< endl;
}
int counter = 0;
while (counter < 11) {
queueNodes(nodes);
counter++;
}
return 0;
}
void queueNodes(vector<vertex>& nodes) {
for (auto& i : nodes) {
cout << endl << i.vertexName << " ";
if (i.incomingEdges == 0) {
i.nextDoorTop->incomingEdges--;
i.nextDoorMiddle->incomingEdges--;
i.nextDoorBottom->incomingEdges--;
cout << "foo";
} else {
cout << "bar";
}
}
}