简体   繁体   English

如何从给定指针的向量中删除元素-C ++

[英]How to delete a element from vector given a pointer to it - C++

If I have a vector that looks like this {a, b, c, d, e, f} and I have a pointer named myPointer and it points to element e , how can I delete e from the vector? 如果我有一个看起来像{a, b, c, d, e, f}的向量,并且我有一个名为myPointer的指针,它指向元素e ,如何从向量中删除e

Here is example code of what I would like to do 这是我想做的示例代码

vector<char> v = {'a', 'b', 'c', 'd', 'e', 'f'};

char *myPointer = &v[4];

// I want to do something like this
v.erase(myPointer);

// Output
// a, b, c, d, f

Can this be done? 能做到吗?

You could use a pointer to the first element to calculate the offset, then use that to create an iterator to pass to std::vector::erase . 您可以使用指向第一个元素的指针来计算偏移量,然后使用该指针创建一个迭代器以传递给std::vector::erase

auto offset = myPointer - v.data();
v.erase(v.begin() + offset);

This assumes myPointer points to an element of v . 假设myPointer指向v的元素。 If not, the behaviour is undefined. 如果不是,则行为是不确定的。


Working example: 工作示例:

#include <vector>
#include <iostream>

int main()
{
    std::vector<int> v{1,2,3,4,5,6,7,8};
    int* p = &v[3];

    v.erase(v.begin() + (p - v.data()));

    for (auto i: v)
        std::cout << i << ' ';

    std::cout << '\n';
}

output: 输出:

1 2 3 5 6 7 8 1 2 3 5 6 7 8

The data stored by a vector is contiguous, so you can convert a pointer to an iterator by: getting a pointer to the first element, doing pointer arithmetic to find the difference and then apply that to begin : vector存储的数据是连续的,因此您可以通过以下方式将指针转换为迭代器:获取指向第一个元素的指针,进行指针算术以找出差异,然后将其应用于begin

assert(v.data() <= mypointer && mypointer < v.data()+v.size());
v.erase(v.begin() + (mypointer - v.data()));

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

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