循环没有给出预期的答案 - 不确定退出/返回/中断
我正在测试一段简单的代码,以便了解如何使用队列(以及实现向量)。循环没有给出预期的答案 - 不确定退出/返回/中断
我写这段代码:
#include "stdafx.h"
#include <iostream>
#include <queue>
struct msgInfo //contains the attributes as gleaned from the original (IP) message
{
int age;
std::string name;
};
using namespace std;
int main()
{
vector<vector<queue<msgInfo>>> nodeInc; //container for messages
int qosLevels = 7; //priority levels
int nodes = 5; //number of nodes
vector<queue<msgInfo>> queuesOfNodes(qosLevels);
int i;
for (i=0; i<nodes; i++)
{
nodeInc.push_back(queuesOfNodes);
}
msgInfo potato, tomato, domato, bomato;
potato.age = 2;
potato.name = "dud";
tomato.age = 3;
tomato.name = "bud";
domato.age = 4;
domato.name = "mud";
bomato.age = 5;
bomato.name = "pud";
nodeInc[2][2].push(potato);
nodeInc[2][2].push(tomato);
nodeInc[2][3].push(domato);
nodeInc[2][3].push(bomato);
for (int j = 0; j < 2; j++) //simple loop for testing: for each round, output the age of only one 'msgInfo'
{
cout << j << endl;
for (int k = (qosLevels-1); k >= 0; k--)
{
if (!nodeInc[2][k].empty())
{
cout << nodeInc[2][k].front().age << endl;
nodeInc[2][k].pop();
return 0;
}
else
break;
}
}
}
我得到的输出是
0
1
但我想获得是
0
4
1
5
我在这里做错了什么?我无法弄清楚我的逻辑错在哪里 - 在我看来,它应该输出属于最高优先级的头两个元素。我认为这与我如何退出循环有关 - 本质上我希望for循环的每一轮在pop'之前只输出一个msgInfo的年龄 - 但我试过退出/返回/ break没有工作。
编辑
我从节点接收消息。这些消息需要根据其属性(节点和优先级)放入队列中。我决定使用vector<vector<queue<msgInfo>>>
来做到这一点 - >本质上节点<优先级<队列的消息>>。当访问这个容器时,我需要它一次输出一个msgInfo的年龄 - msgInfo将成为最高优先级队列的前端。并不是所有的优先级都会被填充,所以它需要从最高优先级级别迭代到最低级别,以便找到相关的元素。
我需要设计一个循环,一次输出这些循环(因为其他处理需要在循环的每一轮之间完成)。
最接近我能得到的是:
for (int j = 0; j < 2; j++) //simple loop for testing: for each round, output the age of only one 'msgInfo'
{
cout << j << endl;
for (i = (qosLevels-1); i >= 0; i--)
{
if (!nodeInc[2][i].empty())
{
cout << nodeInc[2][i].front().age << endl;
nodeInc[2][i].pop();
//return 0; <--------DON'T return. this terminates the program
break;
}
//else
// break;
}
}
返回:
0
4
1
5
正如在评论中指出,从main()
调用return 0;
回报,因此终止程序(实际上是一种和平出口)。
你期望return 0
和break
能做什么?
return 0
退出整个main
函数,因此您的程序在遇到非空队列时会结束。
break
终止最内部的封闭循环(即for (i ...)
)。换句话说,当前的逻辑是:
对于0
的每个j
,1
做:
如果nodeInc[2][qosLevels - 1]
不为空,打印其前和退出程序;否则请不要再尝试i
s,然后再做j
。
我不知道预期的行为是什么,但根据您给出的“预期产出”,您应该用break
替换return 0
,并完全省略else
子句。
谢谢,这是做到了 – sccs 2013-02-21 08:08:17
如果你写下你打算做的事情,会更容易理解你的代码。 – phoeagon 2013-02-21 07:53:19