简体   繁体   English

删除指针数组中的元素(调整大小)

[英]delete element inside pointers array (resize)

Im trying to understand pointers, below my code: 我试图理解我的代码下面的指针:

int main()
{

    int size = 5; //Size of array
    int position = 2; //Position to delete

    int *pointer = new int[size]; //Pointer declaration

    //Populates array with numbers starting at 1 up to size elements (5 in this case)
    for (int i = 0 ; i < size; i++)
    {
        pointer[i] = i+1;
    }

    //Prints existing elements (numbers 1 to 5 in this case)
    for (int i = 0 ; i < size; i++)
    {
        std::cout << pointer[i] << ", ";
    }


    return 0;
}

I know that if I do delete [] pointers; 我知道如果我delete [] pointers; it will delete the array from the memory, but how can I delete just the object inside position 2 or resize the array? 它会从内存中删除数组,但是如何删除仅位置2内的对象或调整数组大小?

You can't do either of those things. 您不能做任何事情。 You can move items around within your existing allocation, and you can make a new allocation, copy items over, and delete the old allocation. 您可以在现有分配中移动项目,也可以进行新分配,复制项目并删除旧分配。

To work with data you should use a container called vector which provides member functions to remove an element or resize. 要处理数据,应使用一个称为vector的容器,该容器提供成员函数以删除元素或调整大小。 A vector is the equivalent in C++ of what most other languages call an "array". 向量在C ++中等同于大多数其他语言称为“数组”的东西。

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

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