我如何在 C++ 中删除/插入数组的元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11825937/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do i delete/insert an element of an array in C++
提问by Zachary Luong
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:
如果我输入例如:3 第三个元素将被删除并替换为下一个值。像这样:
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 i.e "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
非常感谢
回答by Heisenbug
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::vectorinstead.
如果您需要在运行时调整数组大小,请考虑改用std::vector。
回答by Humungus
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 循环迭代都将数组的最后一个元素设置为 0,因此在循环的第一遍之后,它将是{1, 2, 4, 4, 0}
, next {1, 2, 4, 0, 0}
。
简单地将arr[n - 1] = 0;
for 循环排除在外就足够了。同样:
编辑:更新循环控制语句,使其不会越界,谢谢 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. 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.
至于第二个问题:您必须创建一个更大的新数组才能添加任何内容。
您将需要的是malloc
,calloc
和free
功能。熟悉它们和动态分配。一般的想法是malloc
或calloc
一个大小比当前数组大一的数组,将元素复制到要插入另一个元素的空间,插入该元素,然后复制数组的其余部分。之后,不要忘记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.
为简洁起见,省略了分配检查。
类似的方法可以用于第一个问题来改变数组的大小。
回答by imh1j4l
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 中删除或擦除元素
回答by Henrik
Move
移动
arr[n - 1] = 0;
after the loop to get 1; 2; 4; 5; 0:
循环后得到1;2; 4; 5; 0:
for(int i = 2; i < n - 1; i++)
arr[i] = arr[i + 1];
arr[n - 1] = 0;
回答by YePhIcK
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 haveto 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 beyondthe 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)
旁注:虽然您的第一个代码正在移动元素并在该内存块的末尾留下一个未使用的“尾部”,但第二个示例将访问超出为此数组分配的内存块的内存,从而导致内存访问冲突(以及更多比任何体面的操作系统终止您的程序的可能性更大)
回答by learnvst
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.
如果您使用的是 C++,那么您可以使用标准模板库中的容器。您在代码示例中使用的数组是 C 样式数组。虽然在 C++ 代码中使用 C 风格的数组是完全可以接受的,但使用 std::vector 会更好,因为它在运行时调整数组大小方面提供了更大的灵活性。在大多数情况下,C 样式数组和 std::vector 之间的性能差异可以忽略不计。
回答by BLUEPIXY
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
}