イテレータを使用して、リンクされたリストの値を別の外部リンクリスト(現在のメソッドではない)に代入しようとしています。C++イテレータとリンクリスト
LIST_ITER i = temp.begin();
while(bLeft != end)
{
*bLeft = *i;
++i;
++bLeft;
}
bLeftと端部が外部リストの(それぞれ)最初と最後であるのに対し、これは、コードの一部のみ、iは一時リストのためのものであるイテレータです。
しかし、上記のコードでは、奇妙なテキストがたくさんあるところがあります(実際にはMicrosoft Windows Compatibleなどについて言われています)、Unixマシンで実行するとSegmentation障害。
EDIT:
#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
おそらく、あなたは 'temp'に十分なメモリを割り当てていないので、' ++ i'は範囲外で実行されます。 –
どのような種類のイテレータを使用していますか? bLeftが指すリストが空の場合、コードは破損します。 –