0

C++ で STL を使用して、複数のベクトルをマージして、入力ベクトル内の要素の結合である結果のベクトルを作成しようとしています。各入力は既にソートされており、要素は unsigned short です。

「Expression: vector iterator + offset out of range」というエラーが表示されますが、その理由がわかりません。これは、Visual Studio 2013 デバッガーで実行されるデバッグ ビルドです。

コードは次のとおりです。

std::vector <unsigned short> wl, temp;
int iS; std::vector <unsigned short>::iterator oi, it;
for (iS=0; iS<nScans; iS++)
{
    std::vector<unsigned short> sc(scan[iS].wavelength, scan[iS].wavelength + scan[iS].nWavelengths);
    oi=set_union(wl.begin(), wl.end(), sc.begin(), sc.end(), temp.begin());
    wl.assign(temp.begin(), oi); // temp is needed because destination cannot overlap source
}

その意図は、各スキャン (sc) からの波長のベクトルがベクトル wl にマージされることです。(ベクトル wl は、ここには示されていないコードによって unsigned short の C++ 配列にコピーされます)。

4

1 に答える 1

4

tempのサイズは 0 であるため、set_unionその末尾を超えて書き込みます。それをに変更します

set_union(wl.begin(), wl.end(), sc.begin(), sc.end(), std::back_inserter(temp));
wl = temp;
temp.clear();

デモ

更新:ベクトルの温度が自動的にサイズが大きくならないのはなぜですか?
Imaginetempは空で、次のコードが実行されます。

std::vector<unsigned short>::iterator it = temp.begin();
*it = 123; // Undefined behavior
++it;      // UB
*it = 456; // UB

それはまさにそれstd::set_unionがしていることです。指定した出力反復子に書き込み、インクリメントするだけです。ただし、通常のベクター イテレータはアイテムを追加しません。アイテムを追加する必要がありますpush_back。それback_inserterがやっていることであり、それがここで必要とされる理由です。

于 2014-09-24T22:51:05.753 に答える