2011-02-02 80 views
2

所以我試圖使用迭代器將一個鏈接列表的值分配給另一個外部鏈接列表(不在當前方法中)。C++迭代器和鏈接列表

LIST_ITER i = temp.begin(); 
while(bLeft != end) 
{ 
    *bLeft = *i; 
    ++i; 
    ++bLeft; 
} 

這僅僅是代碼的一部分,所述迭代i是用於臨時列表中,而bLeft和端是開始和外部列表的末尾(分別)。

但是,上面的代碼產生了一個奇怪的錯誤,我得到了一堆奇怪的文本(其中一些實際上說了一些關於Microsoft Windows兼容等等),當在Unix機器上運行時只是給出了一個分割故障。

編輯:這裏是全部代碼:

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

using namespace std; 

typedef list<string> LIST;       // linked list type 
typedef LIST::size_type LIST_SIZE;    // size type for list, e.g., unsigned 
typedef LIST::iterator LIST_ITER;     // iterator type 
typedef LIST::value_type LIST_CONTAINS; // type in the list, i.e., a string 

void merge_sort(LIST_ITER beg, LIST_ITER end, LIST_SIZE sz); 
void merge(LIST_ITER bLeft, LIST_ITER bRight, LIST_ITER end); 

int main() 
{ 
LIST l; 
LIST_CONTAINS v; 
// Read in the data... 
while (cin >> v) 
l.push_back(v); 
// Merge the data... 

LIST_ITER i = l.begin(); 
LIST_ITER iEnd = l.end(); 
merge_sort(i, iEnd, v.size()); 
// Output everything... 
for (; i != iEnd; ++i) 
{ 
    cout << *i << '\n'; 
} 
system("pause"); 
} 

void merge_sort(LIST_ITER beg, LIST_ITER end, LIST_SIZE sz) 
{ 
if(sz < 2) 
{ 
    return; 
} 
else 
{ 
    LIST_SIZE halfsz = (distance(beg, end)/2); //half of list size 
    LIST_ITER i1End = beg; //iterator for the end of the first list 
    advance(i1End, halfsz); //advance to the midpoint 
    i2 = i1End++; //iterator for the beginning of the second list 
    --end;//iterator for the end of the second list 

    merge_sort(beg, i1End, halfsz); //recursively pass first list 
    merge_sort(i2, end, halfsz); //recursively pass second list  
} 
merge(beg, i2, end); 
} 

void merge(LIST_ITER bLeft, LIST_ITER bRight, LIST_ITER end) 
{ 

LIST temp; 
LIST_ITER beg = bLeft; 
LIST_ITER halfw = bRight; 
LIST_ITER i = temp.begin(); 


while(beg != bRight && halfw != end) 
{ 
    if(*beg < *halfw) 
    { 
     temp.push_back(*halfw); 
     halfw++; 
    } 
    else 
    { 
     temp.push_back(*beg); 
     beg++; 
    } 
} 

while(beg != bRight) 
{ 
    temp.push_back(*beg); 
    beg++; 
} 
while(halfw != end) 
{ 
    temp.push_back(*halfw); 
    halfw++; 
} 

while(bLeft != end) ///HERE IS THE PREVIOUSLY POSTED CODE 
{ 
    *bLeft = *i; 
    ++i; 
    ++bLeft; 
} 

} 
+0

`bLeft`和`end`是如何初始化的? – AShelly 2011-02-02 20:16:50

+0

也許你沒有爲`temp`分配足夠的內存,所以`++ i`會跑出界限。 – 2011-02-02 20:18:12

+0

你使用了什麼樣的迭代器?如果列表bLeft指向的是空的,代碼將會中斷。 – 2011-02-02 20:18:37

回答

2

不宜迴路測試是:

while (bLeft != end && i != temp.end()) 

你怎麼知道我比其他容器更大?

3

最有可能的原因是源列表中沒有足夠的元素。沒有更多的信息(或上下文),但不可能更精確。

1

爲什麼不使用std::list's assign method?如果這兩個列表中的數據是相同類型的,那真的應該是你所需要的,不是嗎?

1

似乎你想要完成的事情可以用assign函數完成。

exterior.assign(temp.begin(), temp.end()); 

這應該從開始到結束爲外部列表分配臨時列表的值。

0

如果您打算繼續使用臨時列表,請使用std::copy。如果您不是,請使用std::list.splice

0

我想我已經發現了錯誤,它與我如何不必要地增加了一些迭代器(例如不必要地遞減「結束」)並且我的代碼仍然有錯誤,但我需要經過它更多。

感謝您的建議!