2017-02-24 101 views
0

所以我有這個任務要求打印每一個其他值,打印一個跳過一個,但我遇到了麻煩,我所做的只是打印所有的迭代器,需要幫忙。使用迭代器打印一個列表

void print_even(const list<short>& data) 
{ 
    if (data.empty()) 
    { 
     cout << "<>"; 
    } 
    else 
    { 
     list<short>::const_iterator iter = data.cbegin(); 
     cout << "<" << *iter; 
     ++iter; 


     while (iter != data.end()) 
     { 
      cout << ", " << *iter; 
      ++iter; 

     } 
     cout << ">"; 
    } 
} 

回答

1

你需要有if檢查狀態:

int index = 0; 
while (iter != data.end()) 
{ 
    if (index++ % 2) { 
     cout << ", " << *iter; 
    } 
    ++iter; 

} 

這將打印奇數位置。如果您需要打印配對位置,則不需要index++ % 2,您需要(!(index++ % 2))

0

雖然你可以使用%2的方法,你不需要需要,還有其他選擇。

一個選項是爲每個輸出增加兩次。 如果有任何循環遍歷奇數個元素的機會,您需要確保循環仍然正確終止,並且不會跳過結尾。有很多這樣的方式太,一個辦法是檢查結束兩次: -

while (iter != data.end()) 
    {    
     ++iter; // increment without output since first element is handled outside loop 

     if(iter == data.end()) // 2 checks due to 2 increments per loop 
     { 
      break; 
     } 
     cout << ", " << *iter; 
     ++iter; 
    } 

或者你可以有控制是否你輸出一個布爾值: -

bool shouldOutput = false; // starts false as first item already output 
    while (iter != data.end()) 
    { 
     if(shouldOutput) 
     { 
      cout << ", " << *iter; 
     } 
     shouldOutput = !shouldOutput; 
     ++iter; 
    } 

我不是說這些比%2方法好得多,只是指出了其他一些方法。