0

テンプレート化されたコンテナー クラスの容量を減らすコードをいくつか書きました。要素がコンテナーから削除された後、消去関数は、合計スペースの 25% が使用されているかどうか、および容量を半分に減らすと、設定した既定のサイズよりも小さくなるかどうかを確認します。これら 2 つが true を返す場合、downsize 関数が実行されます。ただし、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++;   
}
4

2 に答える 2