2013-03-13 58 views
0

我有2層地圖,其中第二層指向隊列。我想從隊列中提取一定數量的項目(因此也從地圖中提取),但是在正確的位置插入中斷/返回/退出(我不確定在這種情況下使用哪個項目)似乎有問題。在x個循環後退出while循環

這是代碼:

#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 

回答

1

main方法的情況下,exitreturn基本上做同樣的事情。也不建議在循環中進行。

我的建議:

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,但後者更具可讀性。

+0

謝謝,那工作! – sccs 2013-03-13 07:32:06

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: 
+1

[No.別!這是一個陷阱!](http://xkcd.com/292/) – Zeta 2013-03-13 07:13:26

+0

它似乎有點小錯誤 - 如果我改變行數'if(++ countRemoved == 2)goto stop;'to one less than我在地圖中的總元素,它不顯示正確數量的元素。爲什麼會發生? – sccs 2013-03-13 07:16:49