循环未给出预期答案-不确定退出/返回/中断

Loop not giving expected answer - unsure about exit/return/break

本文关键字:退出 不确定 返回 中断 答案 循环      更新时间:2023-10-16

我正在测试一段简单的代码,以便了解如何使用队列(以及练习向量)。

我写了一段代码:

#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 0break做什么?

return 0退出整个main函数,因此一旦遇到非空队列,程序就会结束。

break终止最里面的封闭循环(即for (i ...))。换句话说,您当前的逻辑是:

对于vector<vector<queue<msgInfo>>>1的每个j1执行:

如果nodeInc[2][qosLevels - 1]不为空,则打印其前端和退出程序;否则不再尝试i s,然后执行下一个j

我不知道预期的行为是什么,但根据您给出的"预期输出",应该将return 0替换为break,并完全省略else子句。