2012-08-13 121 views
2

我正在嘗試使用迭代器來遍歷C++中的vector<char*>。我建立了一個應該在最後開始的虛擬程序,並在數字> 0上向後(朝向開始或rend()),並在數字< 0上前進(結束或rbegin()),然後退出如果迭代器已經到達任意一端並且用戶嘗試進一步,它應該重複該末端的元素而不移動迭代器。我的問題是,而不是這樣做,如果用戶試圖運行結束,我只是得到一個段錯誤。這裏是我的代碼:C++中的矢量迭代器

#include <iostream> 
#include <vector> 
#include <stdio.h> 

using namespace std; 

int main(){ 
    vector<char*> vect; 
    char* tmp; 
    for (int i=1; i<=5; i++){ 
     tmp = new char[7]; 
     sprintf(tmp, "hello%d", i); 
     vect.push_back(tmp); 
    } 

    vector<char*>::const_reverse_iterator it = vect.rbegin(); 

    int a; 
    cin >> a; 

    while (a!=0){ 
     if (a>0){ 
      if (it < vect.rend()){ 
       cout << *(++it) << endl; 
      } else{ 
       cout << *it << endl; 
      } 
     } else{ 
      if (it > vect.rbegin()){ 
       cout << *(--it) << endl; 
      } else{ 
       cout << *it << endl; 
      } 
     } 
     cin >> a; 
    } 

    return 0; 
} 

任何人都可以找出問題嗎?

編輯

我忘了,我做了一個微小的變化。我之前的代碼沒有在初始化for循環中填充tmp。已被修復

+0

你知道有內存泄漏在那個代碼中,對嗎? – Fiktik 2012-08-13 15:04:51

+0

是的,我看到了,但它並不重要,因爲這只是dumnmy的代碼 – ewok 2012-08-13 15:17:00

回答

7

問題是rend迭代器指向一個項目通過序列的(反向)結束。解引用它會導致段錯誤:

if (it < vect.rend()){ 
     cout << *(++it) << endl; 
    } else{ 
     cout << *it << endl; // <---- segfault 
    } 

的最小修復可能是

if (it+1 < vect.rend()) 
{ 
    cout << *(++it) << endl; 
} else{ 
    cout << *it << endl; 
} 
+0

這是正確的,但有點難以確切地看到_where_'rend()'是從一個不經意的代碼中取消引用的。建議的行應該替換'if(it Chad 2012-08-13 14:58:03

+0

@查德:謝謝,我補充說明 – Andrey 2012-08-13 15:01:01

0

既然目標,有效的,是不使用過去的最末端位置,我想重鑄問題:它需要兩個迭代器,一個指向所需範圍內的第一個元素,另一個指向最後一個元素。然後力學變得容易:

if (it != end) 
    ++it; 
cout << *it << endl; 

同樣地,去了另一個方向:

if (it != begin) 
    --it; 
cout << *it << endl; 

在哪裏開始和結束都是這樣定義的:

typedef vector<char*>::reverse_iterator iter; 
iter begin = vect.rbegin(); 
iter end = --vect.rend(); // assumes that vect is not empty