从指针擦除指向指针矢量

Erasing from a pointer to a vector of pointers

本文关键字:指针 擦除      更新时间:2023-10-16

对于以下代码:

vector<int*> x;
vector<int*>* p;
// say I initiated x with a couple of integers
p  = &x;
//erases the indicie of the given integer
void erase(vector<int*> &x, int n){
  int i = 0;
  while (*(x[i]) != n){
    i++;
  }
  delete x[i];
  x.erase(x.begin() + i);
}

如果我调用代码erase(*p, 2);我现在想p设置为这个已被擦除的向量的地址......我正在尝试p = &(*p);..但这不起作用,我得到了一个细分错误,有什么想法吗?

你不应该做任何事情。 p仍然指向&x,就像你打电话给erase()之前一样。从矢量中删除元素不会更改矢量的地址。