循环未给出预期答案-不确定退出/返回/中断
Loop not giving expected answer - unsure about exit/return/break
我正在测试一段简单的代码,以便了解如何使用队列(以及练习向量)。
我写了一段代码:
#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循环的每一轮在"弹出"之前只输出一条消息信息的年龄——但我尝试过退出/返回/中断,但没有成功。
编辑
我正在接收来自节点的消息。这些消息需要根据其属性(节点和优先级)放入队列中。我决定使用CCD_ 1来实现这一点->本质上是node<优先级<排队等候消息>>。当访问这个容器时,我需要它一次输出一个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
正如注释中所述,调用return 0;
从main()
返回,因此终止程序(实际上是一种和平退出)。
您希望return 0
和break
做什么?
return 0
退出整个main
函数,因此一旦遇到非空队列,程序就会结束。
break
终止最里面的封闭循环(即for (i ...)
)。换句话说,您当前的逻辑是:
对于vector<vector<queue<msgInfo>>>
1的每个j
,1
执行:
如果nodeInc[2][qosLevels - 1]
不为空,则打印其前端和退出程序;否则不再尝试i
s,然后执行下一个j
。
我不知道预期的行为是什么,但根据您给出的"预期输出",应该将return 0
替换为break
,并完全省略else
子句。
- 不确定要在我的main中放入什么才能使我的代码正常工作
- 不确定如何装饰我的C++库代码以在 C 中使用
- C++功能泄漏内存,我是C++新手,不确定如何解决
- "错误 C0000:语法错误,令牌"<EOF>"处出现意外$end,并且不确定
- 代码在 CodeSignal 中工作不正确。不确定这是否是我的代码缺陷
- 为什么以下代码是不确定的?
- 编译错误:"lvalue required as left operand of assignment" 不确定原因
- 误用指针会产生分段错误。我仍然不确定如何纠正它
- 我不确定为什么代码没有运行,它在编译时抛出错误,说它无法找到 PrintArray()
- 不确定出了什么问题(字符串输入)
- C++睡眠时间不确定
- 在C++中做一个场景问题,我不确定如何处理布尔和if循环
- 代码输出随机符号,我不确定出了什么问题
- 可变值变化,不确定原因
- 有没有办法让C++从 cin 中接收不确定数量的字符串?
- 尝试一次将单个字符读取到大小不确定的数组中
- 我不确定如何引用此神经网络训练方法中的权重
- 为什么循环退出不会?
- 函数参数:不确定排序还是未排序?
- 循环未给出预期答案-不确定退出/返回/中断