0

我编写了一些代码来减少模板化容器类的容量。从容器中删除一个元素后,擦除功能会检查是否有 25% 的总空间正在使用,以及将容量减少一半是否会导致它小于我设置的默认大小。如果这两个返回 true,则缩小函数运行。但是,如果在我处于 const_iterator 循环中间时发生这种情况,则会出现段错误。

再次编辑:我认为这是因为 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

0

为了防止在擦除循环期间出现无效迭代器的问题,您可以使用:

x.erase(itr++);

而不是单独的增量和增量调用(显然,如果您不擦除循环遍历的所有内容,则需要一个 else 案例来增加未擦除的项目。)请注意,这是您需要使用后增量而不是比预增量。

整个事情看起来有点低效。转换为数组的方式表明它只能与某些容器类型一起使用。如果您希望从容器中间进行大量擦除,您可以通过选择不同的容器来避免内存问题;也许列出。

如果您选择向量,您可能会发现调用 shrink_to_fit 是您想要的。

另请注意,erase 有一个返回值,该值将指向擦除后元素的(新)位置。

如果您将迭代器返回到新创建的缩小版本的容器,请注意,与原始容器相比 end() 迭代器不起作用。

于 2016-05-03T17:36:06.070 回答
-1

我发现了段错误问题!

发生的事情是我的 x.end() 正在使用数组的大小(不是容量),其中大小是存储在数组中的数据元素的数量,而不是实际上是大小的容量大批。因此,当它在寻找数组的结尾时,它会将其视为实际结尾之前的众多元素。

现在讨论更有趣的问题!

于 2016-05-03T21:55:43.357 回答