简体   繁体   中英

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; it will delete the array from the memory, but how can I delete just the object inside position 2 or resize the array?

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. A vector is the equivalent in C++ of what most other languages call an "array".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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