简体   繁体   English

删除向量 c++ 的 function

[英]Remove function for vector c++

I have a question regarding the remove() function for vector.我对矢量的 remove() function 有疑问。

As I am trying to implement it in my own vector class.当我试图在我自己的向量 class 中实现它时。 I was wondering how does the remove function works.我想知道删除 function 是如何工作的。

How does the function actually removes the element from the vector? function 如何实际从向量中删除元素? And upon removal does the vector closes the gap created?移除后,向量是否会缩小创建的差距?

EDIT I believe i have gotten the code to work thanks for the help!编辑我相信我已经得到了代码,感谢您的帮助!

template<class T>
bool MyVector<T>::RemoveAt(int i)
{
    if(i>=0 && i<count)
    {
        for(int x=i;x<count;x++)
        {
            arr[x] = arr[x+1];
        }
        pop_back();
        return true;
    }
    return false;
}

If you are talking about vector::erase , than it just moves elements that are to the right of the space to the left by n elements, where n is the size of the space being deleted, and of course it changes size by n.如果您在谈论vector::erase ,那么它只是将空间右侧的元素向左移动 n 个元素,其中 n 是要删除的空间的大小,当然它会将大小更改为 n。

If you are talking about std::remove than there is possible implementation, and I here will describe one of them: the algorithm moves each element that satisfies the condition to the corresponding position, erasing the element that was in this position如果您在谈论std::remove ,则可能存在实现,我在这里将描述其中一个:算法将满足条件的每个元素移动到相应的 position,擦除此 position 中的元素

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

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