【问题标题】:Iterator Returning "Junk" on the Last Element迭代器在最后一个元素上返回“垃圾”
【发布时间】:2016-05-01 19:14:41
【问题描述】:

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

---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;
}

【问题讨论】:

  • 你确定迭代器能正常工作吗?
  • T *m_data = temp_array; - 说真的,这不属于该成员函数中声明的。很确定m_data = temp_array; 会做得更好。
  • WhozCraig - 我认为你是对的。现在我意识到我对 m_data 的错误。

标签: c++ arrays templates dynamic


【解决方案1】:

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

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;

在这里(在上面的代码中)您删除 temp_array 这是您的新数组。所以解决方法是将上面替换为:

  delete [] m_data;
  m_data = temp_array;

【讨论】:

  • 好的,谢谢!显然,我在考虑解除分配的问题。只是一个新手,仍然在这里为指针而苦苦挣扎。非常感谢!
  • @swing 尝试使用unique_ptr&lt;T[]&gt; -- 资源跟踪工作少得多。当原始T* 代码在某些情况下会导致 UB 时,它会立即生成错误。
【解决方案2】:

当你真的想使用类的 m_data 时,你在 resize() 中定义了一个变量 m_data。

【讨论】:

    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 2013-03-19
      • 2017-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-08
      • 2013-02-20
      • 2011-02-21
      相关资源
      最近更新 更多