简体   繁体   English

如何避免插入函数中的指针无效?

[英]How do I avoid pointer invalidation in my insert function?

In my data structures course, we are creating a basic vector class. 在我的数据结构课程中,我们正在创建一个基本的向量类。 In my header, there is a member function for inserting new values into the vector. 在我的标头中,有一个成员函数,用于将新值插入向量中。 If the capacity of my vector is big enough for the insertion of one value, the program runs fine. 如果向量的容量足以插入一个值,则程序运行良好。 However, if the vector needs to grow, I run into pointer errors. 但是,如果向量需要增长,则会遇到指针错误。 After hours of trying to figure out what was happening, I believe that I'm running into a problem with invalidating iterators. 经过数小时的尝试来弄清楚发生了什么,我相信我在使迭代器失效方面遇到了问题。

Here are my insert function, and reserve function: 这是我的插入功能和保留功能:

// Insert "item" before "pos", and return iterator referencing "item"

iterator insert (iterator pos, const T& item)
{

if (m_size ==  m_capacity)
  {
  reserve(m_capacity * 2);
  }

T * endOfArray = (end());

while (endOfArray != pos)
  {
  *(endOfArray) = *(endOfArray - 1);
  --endOfArray;
  }
++m_size;
*pos = item;

return (pos);
}

void reserve (size_t space) {
if (space < m_capacity)
  {
  return;
  }

T *temp_array = new T[space]; 

std::copy(begin(), end(), temp_array);
m_array = new T[space];
std::copy(temp_array, (temp_array + m_size), m_array);
m_capacity = space;
delete [] temp_array;
} 

As you can see, if the insert function calls to have the capacity of the vector increased, then the "pos" iterator invalidates. 如您所见,如果插入函数调用以增加向量的容量,则“ pos”迭代器无效。 How can I get around this problem? 我怎样才能解决这个问题?

Change the pos iterator into an index instead, and use that. pos迭代器改为索引,然后使用它。

size_t index = pos - begin();
// do resize
pos = begin() + index;

If you're worried about iterators invalidating in general, don't. 如果您担心迭代器通常会失效,请不要这样做。 It's unavoidable, at least in this style of dynamic array, and std::vector works exactly the same. 这是不可避免的,至少在这种形式的动态数组中, std::vector工作原理完全相同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM