2013-08-27 175 views
0

我經常需要一個像do-while-do循環的東西。在我執行這個概念的那一刻,像這樣:概念do-while-do循環

Instructions part 1 (for instance: read data) 
while(Condition){ 
    Instructions part 2 (save data) 
    Instructions part 1 (read next data) 
} 

我必須兩次寫第1部分,這很醜。是否有可能擺脫重複? 我認爲一個概念是這樣的:

do{ 
    Instructions part 1 
} while (Condition) do { 
    Instructions part 2 
} 
+0

只有一個'for'循環,請參閱我的回答 – Walter

+1

這有時被稱爲「循環半」。 –

回答

3

我寧願只有一個讀的方法/取

類似:

bool readData(SomeObject & outPut) { 
    perform read 
    return check-condition 
} 

while (!readData (outObj)) { 
    // work on outObj 
} 
+0

'while(!readData(outObj))''。比較「bool」與「true」或「false」是毫無意義的。 (並且類型拼寫爲'bool',而不是'boolean'。) –

+0

你是對的,最近抱歉太多了,但是sice是僞代碼,我想我沒有想過關於這裏的語法,只是想法。 – BigMike

4

我通常做解決類似的問題:

while (true) { 
    Instructions part 1 
    if (!Condition) { 
    break; 
    } 
    Instructions part 2 
} 
+2

或'for(;;)'對於那些不喜歡的人(true) –

+0

也許,但這不是一個很好的解決方案,至少在可讀性方面。 BigMike的解決方案要好得多。 –

+0

@JamesKanze同意我喜歡他的解決方案 –

1

如果將part 1放入一個返回01的函數,你可以這樣做:

while (DoPart1()) 
{ 
    DoPart2(); 
} 
+0

誰低調正確的答案,而不是陳述什麼? –

0

你可以定義一個小模板函數

template<typename Part1, typename Condition, typename Part2> 
void do_while_do(Part1 part1, Condition condition, Part2 part2) 
{ 
    part1(); 
    while(condition()) { 
    part2(); 
    part1(); 
    } 
} 

與功能,仿函數,或lambda表達式使用它,即

some_type tmp; 
do_while_do([&]() { read(tmp); }, 
      [&]() { return cond(tmp); }, 
      [&]() { save(tmp); }); 

有,當然,從lambda捕獲開銷,但至少沒有重複(可能冗長)代碼爲part1。當然,可以對模板進行細化以處理參數(例如,示例中的tmp)。