私は、テンプレートコンテナクラスの容量を減らすためにいくつかのコードを書いています。要素がコンテナから削除された後、消去機能は総スペースの25%が使用されているかどうかをチェックし、容量を半分に減らすと設定したデフォルトサイズよりも小さくなるかどうかをチェックします。これらの2つが真である場合、ダウンサイズ機能が実行されます。しかし、私がconst_iteratorループの途中にいるときにこれが発生した場合、私はsegfaultを取得します。コンテナテンプレートクラス - コンテナサイズを小さくする
もう一度編集してください:const_iteratorポインタが古い配列を指していて、downsize()によって作成された新しいポインタを指す必要があるからだと思います...
消去ループ中に無効化されたイテレータの問題を防ぐためtemplate <class T>
void sorted<T>::downsize(){
// Run the same process as resize, except
// in reverse (sort of).
int newCapacity = (m_capacity/2);
T *temp_array = new T[newCapacity];
for (int i = 0; i < m_size; i++)
temp_array[i] = m_data[i];
// Frees memory, points m_data at the
// new, smaller array, sets the capacity
// to the proper (lower) value.
delete [] m_data;
m_data = temp_array;
setCap(newCapacity);
cout << "Decreased array capacity to " << newCapacity << "." << endl;
}
// Implementation of the const_iterator erase method.
template <class T>
typename sorted<T>::const_iterator sorted<T>::erase(const_iterator itr){
// This section is reused from game.cpp, a file provided in the
// Cruno project. It handles erasing the element pointed to
// by the constant iterator.
T *end = &m_data[m_capacity]; // one past the end of data
T *ptr = itr.m_current; // element to erase
// to erase element at ptr, shift elements from ptr+1 to
// the end of the array down one position
while (ptr+1 != end) {
*ptr = *(ptr+1);
ptr++;
}
m_size--;
// Once the element is removed, check to
// see if a size reduction of the array is
// necessary.
// Initialized some new values here to make
// sure downsize only runs when the correct
// conditions are met.
double capCheck = m_capacity;
double sizeCheck = m_size;
double usedCheck = (sizeCheck/capCheck);
int boundCheck = (m_capacity/2);
if ((usedCheck <= ONE_FOURTH) && (boundCheck >= DEFAULT_SIZE))
downsize();
return itr;
}
// Chunk from main that erases.
int i = 0;
for (itr = x.begin(); itr != x.end(); itr++) {
if (i < 7) x.erase(itr);
i++;
}
私は残念なことに、どのようなコンテナであるかについてはあまり選択肢がありません。それは学校プロジェクトのために、彼らは私にこのメソッド/データメンバーの長いリストを与えて、それがこのように実装すると言いました。 – swingonaspiral