简体   繁体   中英

How do i delete/insert an element of an array in C++

So first question, i have this array here:

arr[] = {1; 2; 3; 4; 5}

and if i type in for example: 3 the third element will be deleted and replaced by the next value. like this:

arr[] = {1; 2; 4; 5}

i have got this code here:

for(int i = 2; i < n; i++)
{
    arr[i] = arr[i + 1];
    arr[n - 1] = 0;
}

but the outcome is

arr[] = {1; 2; 4; 0; 0}

please fix the code

second question, i will type in "3" as well but instead of delete the third element and replace it, i have to insert a new third element ie "50" so that:

arr[] = {1; 2; 3; 4; 5}

will become:

arr[] = {1; 2; 50; 3; 4; 5}

I'm still a noob at programming and C++ and this is my first question so please answer nicely :D

Thanks alot

No, the element will never be "deleted". The array size is determined at compile time and will be fixed.

If you need to resize your array size at runtime, consider using std::vector instead.

The problem in the first question is that you're setting the last element of the array to 0 every iteration of the for cycle, so after the first pass of your cycle, it will be {1, 2, 4, 4, 0} , next {1, 2, 4, 0, 0} .
Simply putting the arr[n - 1] = 0; out of the for loop will suffice. Likewise:
EDIT: updated the loop control statement so it doesn't go out of bounds, thanks hmjd

for(int i = 2; i < n-1; i++) 
{
    arr[i] = arr[i + 1];   
}
arr[n - 1] = 0;

The element will not be deleted per se, it will just be set to 0 and the rest will be shifted to the left.

As for the second question: You will have to create a new array with a bigger size to add anything.
What you will need are the malloc , calloc and free functions. Get familiar with them and dynamic allocation in general. The general idea is to malloc or calloc an array of size one bigger than the current array, copy the elements up to the space where you want to insert another element, insert that one and then copy the rest of the array. After that, don't forget to free the old array and setting it's pointer to the new one.

int size = 4;
int arr[] = (int *) calloc(size, sizeof(int));
int insertTo = 2;
int insert = 50;
int tempArr[] = (int *) calloc(size+1, sizeof(int));
for(int i = 0, int j = 0; i < size; i++, j++) {
    if(j == insertTo) {
        tempArr[j] = insert;
        i--; //to offset the cycle incrementation
    } else {
        tempArr[j] = arr[i];
    }
}
free(arr);
arr = tempArr;
size++; // Don't forget to update the size

left out the allocation checks for brevity sake.
Similar approach could be used for the first question to change the size of the array.

Move

arr[n - 1] = 0; 

after the loop to get 1; 2; 4; 5; 0:

for(int i = 2; i < n - 1; i++)
    arr[i] = arr[i + 1];
arr[n - 1] = 0; 

Using the Standard C++ Library Functions for insert or delete an array element and resize it.

For Insert an element in an array std::vector::insert

For remove or erase an element from an array std::vector::erase

arr[] = {1; 2; 3; 4; 5} arr[] = {1; 2; 3; 4; 5} will allocate exactly enough memory to hold 5 (no less, no more) integer values.

When you shift elements around in your code you are doing exactly that - shifting. No "memory" is freed or added with those operations;

If you truly need to change the size of your array as a result of such insert/delete operation you would have to allocate a new array of an appropriate size and copy data from your old array into that new one (and remember to free up the no-longer-used memory of the first array, if appropriate).

Welcome to C++, where an engineer is in charge of managing resources (unlike so many scripting or otherwise "high-level" languages out there).

Side note: while your first code is shifting elements and leaves an unused "tail" at the end of that memory block the second example will access memory that is beyond the memory block allocated for this array, resulting in a memory access violation (and more than likely in termination of your program by any decent OS)

If you are using C++ then the containers in the standard template library are available to you. The arrays that you use in your code examples are C-style arrays. While it is perfectly acceptable to use C-style arrays in your C++ code, you'd be much better of using say std::vector, as it allows for much more flexibility in terms of run-time resizing of arrays. In most coses, there is a negligible perfoamance difference between C-style arrays and std::vector.

use vector

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

template<typename T>
void print(const vector<T> &v){
    typename vector<T>::const_iterator it;
    for(it=v.begin(); it!=v.end(); ++it)
        cout << *it << ' ';
    cout << endl;
}

int main (){
    const int arr[] = {1, 2, 3, 4, 5};
    const int size = sizeof(arr)/sizeof(int);

    vector<int> v(&arr[0], &arr[size]);

    v.erase(v.begin() + 2);
    print(v);//1 2 4 5

    v.insert(v.begin()+2, 3);
    print(v);//1 2 3 4 5
    v.insert(v.begin()+2, 50);
    print(v);//1 2 50 3 4 5
}

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