0

我有两层地图,第二层指向一个队列。我想从队列(以及地图)中提取一定数量的项目,但在正确的位置插入中断/返回/退出(我不确定在这种情况下使用哪个)似乎有问题.

这是代码:

#include <iostream>
#include <queue>
#include <map>

using namespace std;

int main()
{
    typedef std::queue<int> MessageQueue;
    typedef std::map<int, MessageQueue> PriorityMap;
    typedef std::map<int, PriorityMap> ClientMap;

    ClientMap clients;

    int priorities = 7;

    clients[10][1].push(1);
    clients[10][1].push(2);
    clients[10][5].push(3);
    clients[10][7].push(3);

    for (int j = 1; j<3; j++) //this determines how many times an element will be 'popped' from a queue
    {
        while (!clients[10].empty())
        {
            for (int i = priorities; i > 0; i--)
            {
                while (clients[10].find(i) != clients[10].end())
                {
                    cout << "priority " << i << endl;
                    cout << clients[10][i].front() << endl;
                    clients[10][i].pop();

                    if (clients[10][i].empty())
                        clients[10].erase(i);

                }

            }

            break; //I don't know where this should go in order for the while loop to stop executing after an element has been popped
        }

    }

    return 0;
}

有了这个结果

priority 7
3
priority 5
3
priority 1
1
priority 1
2

但我想要的结果是

priority 7
3
priority 5
3
4

2 回答 2

1

main方法的上下文中,exit基本上return做同样的事情。都不建议在循环中间进行。

我的建议:

bool done = false;
for (...; ... && !done; ...)
{
   while (... && !done)
   {
      ...
      done = true;
      ...
   }
}

或者,在您的问题的背景下:

int count = 2;
for (int j = 1; j<3 && count > 0; j++)
{
   while (!clients[10].empty() && count > 0)
   {
      for (int i = priorities; i > 0 && count > 0; i--)
      {
         while (clients[10].find(i) != clients[10].end() && count > 0)
         {
            ...
            count--;
            ...
         }
      }
   }
}

我知道你可以&& count代替&& count > 0,但后者更具可读性。

于 2013-03-13T07:11:49.563 回答
0

而不是外部循环,使用计数器和goto

int countRemoved = 0;
while (!clients[10].empty())
{
    for (int i = priorities; i > 0; i--)
    {
        while (clients[10].find(i) != clients[10].end())
        {
            cout << "priority " << i << endl;
            cout << clients[10][i].front() << endl;
            clients[10][i].pop();
            if (clients[10][i].empty())
               clients[10].erase(i);
            if( ++countRemoved == 2 ) goto stop;
       }
    }
}
stop:
于 2013-03-13T07:11:36.830 回答