简体   繁体   English

如何在C ++中删除/插入数组元素

[英]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. 如果我输入例如:3,第三个元素将被删除并替换为下一个值。 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: 第二个问题,我也会键入“3”,但不是删除第三个元素并替换它,我必须插入一个新的第三个元素,即“50”,以便:

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 我仍然是编程和C ++的菜鸟,这是我的第一个问题所以请你好好回答: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. 如果需要在运行时调整数组大小,请考虑使用std :: vector

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} . 第一个问题中的问题是你在for循环的每次迭代中将数组的最后一个元素设置为0,所以在循环的第一次传递之后,它将是{1, 2, 4, 4, 0} ,下一个{1, 2, 4, 0, 0}
Simply putting the arr[n - 1] = 0; 简单地把arr[n - 1] = 0; out of the for loop will suffice. 超出for循环就足够了。 Likewise: 同样:
EDIT: updated the loop control statement so it doesn't go out of bounds, thanks hmjd 编辑:更新循环控制语句,因此它不会超出范围,谢谢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. 该元素本身不会被删除,它只会被设置为0而其余元素将被移动到左侧。

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. 您需要的是malloccallocfree函数。 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. 一般的想法是malloccalloc是一个比当前数组大一号的数组,将元素复制到你想要插入另一个元素的空间,插入那个元素,然后复制数组的其余部分。 After that, don't forget to free the old array and setting it's pointer to the new one. 之后,不要忘记free旧数组并将其指针设置为新数组。

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; 循环后获得1; 2; 2; 4; 4; 5; 5; 0: 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. 使用标准C ++库函数插入或删除数组元素并调整其大小。

For Insert an element in an array std::vector::insert 用于在数组std :: vector :: insert中插入元素

For remove or erase an element from an array std::vector::erase 用于从数组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. arr[] = {1; 2; 3; 4; 5}将分配足够的内存来保存5(不少于,不多于)整数值。

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). 欢迎使用C ++,其中工程师负责管理资源 (与许多脚本或其他“高级”语言不同)。

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. 如果您使用的是C ++,则可以使用标准模板库中的容器。 The arrays that you use in your code examples are C-style arrays. 您在代码示例中使用的数组是C样式数组。 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. 虽然在C ++代码中使用C风格的数组是完全可以接受的,但是使用say std :: vector要好得多,因为它可以在运行时调整数组大小方面提供更大的灵活性。 In most coses, there is a negligible perfoamance difference between C-style arrays and std::vector. 在大多数coses中,C风格的数组和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
}

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

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