2015-02-23 31 views
1

我有這樣的代碼:While循環不等於性病::隊列大小

std::queue<unsigned int> offsets; 
// (fill offsets here) 

DEBUG(std::to_string(offsets.size())) // print offsets.size() to console 
int iterations = 0; 

while (!offsets.empty()) 
{ 
    iterations++; 

    unsigned int currOffset = offsets.front(); 
    offsets.pop(); 

    if (currOffset == 0) 
    { 
     DEBUG("breaking from while loop") 
     break; 
    } 

    // do something with currOffset 
} 

DEBUG(std::to_string(iterations)) 

出於某種原因,iterations總是不等於offsets.size()。我不確定這是爲什麼。在我的測試應用程序中,offsets.size() == 28,但是iterations == 11。我只在這個應用程序中從while循環中斷開。

任何想法爲什麼會發生這種情況?非常感謝幫助。

+0

你能解釋爲什麼你會期待'迭代'等於'偏移量。 – juanchopanza 2015-02-23 19:45:02

+0

因爲只要'offsetsets.empty()!= true',while循環應該繼續。因此'iterations'應該增加每個循環,因此等於'offsetset()'。至少這就是我期待它的工作原理...... – 2015-02-23 19:53:39

+3

不,因爲你的循環中間有一個'break'。 – juanchopanza 2015-02-23 19:54:29

回答

3

由於第11個偏移量爲零,並且在循環到達數據結構的末尾之前觸發條件中斷?

無論是那個還是// do something with currOffset都涉及從隊列中彈出更多東西。

1

if if break()== 0,不需要爲空。

while (!offsets.empty()) 
{ 
    iterations++; 

    unsigned int currOffset = offsets.front(); 
    offsets.pop(); 

    if (currOffset == 0) // *** Here is the problem *** 
    { 
     DEBUG("breaking from while loop") 
     break; 
    } 

    // do something with currOffset 
}