所以我試圖使用迭代器將一個鏈接列表的值分配給另一個外部鏈接列表(不在當前方法中)。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;
}
}
`bLeft`和`end`是如何初始化的? – AShelly 2011-02-02 20:16:50
也許你沒有爲`temp`分配足夠的內存,所以`++ i`會跑出界限。 – 2011-02-02 20:18:12
你使用了什麼樣的迭代器?如果列表bLeft指向的是空的,代碼將會中斷。 – 2011-02-02 20:18:37