2015-05-04 163 views
0

我正在使用C++ stl自定義定義的結構列表,我有一個遍歷該列表的迭代器,但是在某一點上,我需要遞減並返回列表中的幾個條目。我試過了 - 但那只是給了我一個分段錯誤。有沒有其他的方式來做到這一點。如何在C++中遞減迭代器?

我也試過這個std::advance(cur_instruc, a);

這裏是迭代的樣子:

#include <iostream> 
#include <string> 
#include <list> 

using namespace std; 

typedef struct { 
    int instruction_ptr; 
    int token; 
    std::string instruction; 
    std::string value; 
} decoraded_nodes; 

int main() { 
    std::list<decoraded_nodes> instruction_list; 
    std::list<decoraded_nodes>::iterator it; 
    it = instruction_list.begin(); 

    decoraded_nodes a; 
    a.instruction_ptr = 1; 
    a.token = 1; 
    a.instruction = "1"; 
    a.value = "2"; 

    decoraded_nodes b; 
    b.instruction_ptr = 1; 
    b.token = 1; 
    b.instruction = "1"; 
    b.value = "1"; 

    decoraded_nodes c; 
    c.instruction_ptr = 1; 
    c.token = 1; 
    c.instruction = "1"; 
    c.value = "3"; 

    instruction_list.insert(it, a); 
    instruction_list.insert(it, b); 
    instruction_list.insert(it, c); 

    bool aa = false; 
    int bb = 0; 

    for (std::list<decoraded_nodes>::iterator cur_instruc = instruction_list.begin(), 
     end = instruction_list.end(); 
     cur_instruc != end; ++cur_instruc) { 
     cout << cur_instruc->value; 

     bb++; 

     if (bb == 1) { 
      aa = true; 
     } 

     if (aa) { 
      cur_instruc--; 
      aa = false; 
     } 

    } 

    return 0; 
} 
+3

只要你不減少它的開始,並且你不會使迭代器失效(通過擦除它引用的元素),那應該沒問題。你可以發佈[足夠的代碼](http://stackoverflow.com/help/mcve)來演示這個問題嗎? –

+0

上面的代碼實際上現在工作... – Pete

+0

那麼你爲什麼發佈它?請張貼演示問題的測試案例。沒有這一點,就不可能猜出可能會出現什麼問題。 –

回答

1

這是一個壞主意,改變循環「的」變量(在這種情況下 - 迭代器)內循環。嘗試在循環中創建新的迭代器,當你需要返回並使用這個新創建的迭代器時。