我正在测试一段简单的代码,以便了解如何使用队列(以及实用的向量)。
我写了这段代码:
#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'-ing之前输出一个msgInfo的年龄 - 但我尝试退出/返回/中断它没用。
修改
我正在接收来自节点的消息。这些消息需要根据其属性放入队列:节点和优先级。我决定使用vector<vector<queue<msgInfo>>>
来执行此操作 - &gt;基本上节点&lt;优先级&lt;消息队列&gt;取代。当访问这个容器时,我需要它一次输出一个msgInfo的年龄 - msgInfo将是最高优先级的队列的前面。并非所有优先级都将被填充,因此需要从最高优先级迭代到最低级才能找到相关元素。
我需要设计一个循环,一次输出这一个循环(因为需要在循环的每一轮之间进行其他处理)。
答案 0 :(得分:0)
您希望return 0
和break
做什么?
return 0
退出整个main
函数,因此一旦遇到非空队列,程序就会结束。
break
终止最内层的封闭循环(for (i ...)
)。换句话说,您当前的逻辑是:
对于j
的{{1}} 0
,1
执行:
如果nodeInc[2][qosLevels - 1]
不为空,请打印其正面和退出程序;否则请再试i
s并执行下一个j
。
我不知道预期的行为是什么,但根据您提供的“预期输出”,您应该将return 0
替换为break
,并完全省略else
子句
答案 1 :(得分:0)
我能得到的最接近的是:
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
正如评论中所述,调用return 0;
从main()
返回并因此终止该程序(实际上是一个和平的退出)。