迭代器返回最后一个元素上的"Junk"

Iterator Returning "Junk" on the Last Element

本文关键字:Junk 元素 返回 最后一个 迭代器      更新时间:2023-10-16

我正在处理一些动态分配的数组,我知道这一定是数组的某种范围问题,但我不知道它是什么。当迭代器到达最终相关的数据点时,取消引用指向元素的指针每次只会打印垃圾。m_data是保存数据的数组,并且类型为T,因为它是容器模板。如有任何建议,我们将一如既往地不胜感激。以下是一些相关的片段:

---From sorted.cpp---
template <class T>
typename sorted<T>::const_iterator sorted<T>::insert(T data){
  if (m_size == m_capacity){    
    cout << "Resizing array." << endl;
    resize();
  }
  cout << "Adding " << data << " to array." << endl;
  m_size++;
  m_data[m_size - 1] = data;
  if (m_size > 10){ // This test output works fine.
    cout << "Array should be: " << endl;
    for (int i = 0; i < 11; i++)     
      cout << m_data[i] << " ";
    cout << endl; 
  }
  return const_iterator(&m_data[m_size - 1]);   
}
template <class T>
void sorted<T>::resize(){
  int newCapacity = (2 * m_capacity);
  T *temp_array = new T[newCapacity];
  for (int i = 0; i < m_capacity; i++)
    temp_array[i] = m_data[i];
  T *m_data = temp_array;
  delete [] temp_array;
  setCap(newCapacity);
}
---From test file---
int main() {
  sorted<int> x;
  sorted<int>::const_iterator itr;
  // append some values into my_array x
  for (int i = 1; i < 12 ; i++ ) 
    x.insert( (i*i) % 19 );
  // my_array does not keep items in order
  cout << "my_array x:" << endl;
  for (itr = x.begin(); itr != x.end(); itr++)
    cout << *itr << " ";
  cout << endl << endl; 
  return 0;
}

您的调整大小看起来可疑:

void sorted<T>::resize(){
  int newCapacity = (2 * m_capacity);
  T *temp_array = new T[newCapacity];

所以temp_array是一个具有新尺寸的新阵列

  for (int i = 0; i < m_capacity; i++)
    temp_array[i] = m_data[i];

上面您已经将旧数据复制到新阵列

  T *m_data = temp_array;
  delete [] temp_array;

在这里(在上面的代码中),您删除了temparray,它是您的新数组。因此,修复方法是将以上内容替换为:

  delete [] m_data;
  m_data = temp_array;

当您真正想要使用类的m_data时,您正在resize()中定义变量m_data。

我刚刚意识到m_data不是指向动态分配的数组的指针,而是数组本身。那是我的问题前台