2011-08-11 49 views
1

我有一個很奇怪的錯誤,我似乎無法弄清楚。我把它縮小到一小段代碼(除非編譯器重新排序我的語句,我不相信這是真的)。非常奇怪的掛在一個for循環初始化

... 
std::cout << "here"<< std::endl; 
std::vector<int>::iterator n_iter; 
std::vector<int>::iterator l_iter; 
std::cout << "here?" << std::endl; 
for(n_iter = n.begin(), std::cout << "not here" ; std::cout << "or here" && n_iter < n.end(); n_iter++) 
{ 
    std::cout << "do i get to the n loop?"; 
    ... 
} 

當我運行此,我首先看到的「這裏」,第二個「在這裏嗎?」,但我不明白的「不在這裏」或「這裏或」輸出。而且我絕對不會得到「我到達n循環嗎?」。

奇怪的是,我的程序工作(這幾乎用了整個CPU核......),但它並沒有結束,它只是掛起。

我試過使用鏗鏘聲++和g ++,而我沒有使用任何優化。我已經安裝了boost庫(並使用boost_program_options部分)以及犰狳。但我不認爲編譯器應該被重新排序的東西...

碰巧使用或不使用for循環聲明裏面的cout調用,它不只是跳過循環。

矢量「n」的長度至少爲1,並且由boost_program_options調用給出。

任何想法?

+0

我跑你的代碼,它運行正常(我得到的輸出'不hereor heredo我到n個循環?或here')。這可能是你在循環內部或代碼頂部的'...'內所做的事情。 –

+1

我的猜測是它是這樣做的......。它可以確定一些事情,但是你沒有看到它,因爲它會在沒有刷新輸出的情況下進入一個無限循環。 - 出於這個原因,使用'cerr'作爲調試輸出。 – UncleBens

回答

3

您應該嘗試的第一件事是在每個字符串之後輸出std::endl。這會刷新輸出的緩衝區。

+0

這是...謝謝。 –

2

下面的程序(其中有你那沒有一些額外的新行):

#include <string> 
#include <iostream> 
#include <vector> 

int main() { 
    std::vector<int> n; 
    n.push_back(3); 
    n.push_back(3); 
    n.push_back(3); 

    std::cout << "here"<< std::endl; 
    std::vector<int>::iterator n_iter; 
    std::vector<int>::iterator l_iter; 
    std::cout << "here?" << std::endl; 

    for(n_iter = n.begin(), std::cout << "not here\n" ; std::cout << "or here\n" && n_iter < n.end(); n_iter++) 
    { 
     std::cout << "do i get to the n loop?\n"; 
    } 
} 

具有以下的輸出:

[5:02pm][[email protected] /tmp] make foo 
g++  foo.cc -o foo 
[5:02pm][[email protected] /tmp] ./foo 
here 
here? 
not here 
or here 
do i get to the n loop? 
or here 
do i get to the n loop? 
or here 
do i get to the n loop? 
or here 

這似乎是你所期望的,所以我我不確定你的問題在哪裏,但它可能是跳過的代碼。