从 C++ 数组中删除元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4023011/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 14:18:24  来源:igfitidea点击:

Delete element from C++ array

c++arrays

提问by Vamsi Krishna B

Please tell me how to delete an element from a C++ array.

请告诉我如何从 C++ 数组中删除一个元素。

My teacher is setting its value to 0, is that correct?

我的老师将其值设置为 0,对吗?

回答by KevenK

You can't really "delete" an element from a C++ array.

你不能真正从 C++ 数组中“删除”一个元素。

However, if the array consists of pointers, you can delete the object that a specific element points to.

但是,如果数组由指针组成,则可以删除特定元素指向的对象。

In your teacher's case, it will be important to make note of whether the objects of the array are dynamically allocated (using the newoperator in C++) or not. He may simply be setting his values to 0as an indicator that the value is no longer valid.

在您老师的情况下,重要的是要注意数组的对象是否是动态分配的(使用newC++ 中的运算符)。他可能只是将他的值设置0为该值不再有效的指标。

Without actual source code, this is as much as I can help you with.

没有实际的源代码,这就是我可以为您提供的帮助。

回答by The Archetypal Paul

If you're talking about a normal array. e.g.

如果你在谈论一个普通的数组。例如

int array[100];

then you can't "delete" an eleement, since the array always has 100 elements (in this example).

那么你不能“删除”一个元素,因为数组总是有 100 个元素(在这个例子中)。

So it depends on the interpretation your program makes of the array values. If your teacher is consistently using a value of 0 to mean non-existent element, everything will work and so that's as correct as any other approach.

所以这取决于你的程序对数组值的解释。如果您的老师始终使用 0 值来表示不存在的元素,那么一切都会正常工作,因此这与任何其他方法一样正确。

回答by CashCow

You canremove an element from a vector such that the element is no longer there and all the other elements shift a position.

可以从向量中删除一个元素,这样该元素不再存在并且所有其他元素都移动一个位置。

struct counter
{
   int x;
   int operator()() { return x++; }
   counter() : x(0) {}
};

std::vector<int> v;
std::generate_n( std::back_inserter(v), 8, counter() );
std::copy(v.begin(), v.end(), std::ostream_iterator<int>(cout, " "));
std::cout << '\n';
v.erase( v.begin() + 4 );

std::copy(v.begin(), v.end(), std::ostream_iterator<int>(cout, " "));
std::cout << '\n';

Should output:

应该输出:

0 1 2 3 4 5 6 7

0 1 2 3 4 5 6 7

0 1 2 3 5 6 7

0 1 2 3 5 6 7

(assume all necessary headers included and main function body etc).

(假设包含所有必要的头文件和主函数体等)。

Note that if you have a vector of pointers which were allocated with new, you would have to possibly call delete on the pointer before it was erased from the vector. (This depends on whether the vector manages the lifetime of these pointers). If you have a vector of boost::shared_ptr you will not need to manage the deletion.

请注意,如果您有一个用 new 分配的指针向量,则可能必须在指针从向量中擦除之前调用 delete 。(这取决于向量是否管理这些指针的生命周期)。如果您有 boost::shared_ptr 向量,则无需管理删除。

回答by Benjamin Lindley

If the array is not intended to be sorted, a quick and easy way is to copy the last element to the position of the element to be deleted, then reduce the element count by 1.

如果不打算对数组进行排序,一种快速简便的方法是将最后一个元素复制到要删除元素的位置,然后将元素计数减 1。

回答by Bharat Wadhawan

   :
    int main()
{   
    int a[100],x,i;
    cout<<"enter the no. of elements(max 100): ";
    cin>>x;
    for(i=0;i<x;i++)
    {
        cout<<"enter "<<i+1<<" element: ";
        cin>>a[i];
        cout<<endl;
    }
    cout<<"your array: "<<endl;
    for(i=0;i<x;i++)
    {
        cout<<a[i]<<endl;
    }
    cout<<"enter the element you want to delete: ";
    int b,flag,pos;
    cin>>b;
    for(i=0;i<x;i++)
    {
        if(b==a[i])
        {
            flag=1; pos=i;
        }
        else
        {
            flag=0;
        }
    }
    if(flag==0)
    {
        cout<<"element not found nothing to delete....";
    }
    for(i=0;i<x-1;i++)
    {
        if(i<pos)
        {
            a[i];
        }
    else if(i>=pos)
    {
        a[i]=a[i+1];
    }
    }
    cout<<"new array:"<<endl;
    for(i=0;i<x-1;i++)
    {
        cout<<a[i]<<endl;
    }
    return 0;
}

回答by Ishmeet Singh

scanf("%ld",&x);//x position where we have to delete
if(x==n-1) {
   n-=1;

}
else {
   n-=1;
   for (int i = x; i < n; i++) {
        /* code */
        A[i]=A[i+1];
   }
}

回答by Bj?rn Pollex

Setting it to zero will still make that zero appear when you iterate over the array, or when you access it by index. If you do not want that, you have to copy all elements after the one you deleted one step towards the beginning of the array.

将它设置为零仍然会在您遍历数组或通过索引访问它时出现零。如果您不希望那样,则必须将所有元素复制到您向数组开头一步删除的元素之后。

回答by B?ови?

1) If you have an array of pointers, then like this :

1)如果你有一个指针数组,那么像这样:

// to create an array :
std::vector< int* > arr( 10, NULL );
for ( std::vector< int* >:iterator it=arr.begin; arr.end() != it; ++ it )
{
  *it = new int( 20 );
}
// to delete one element
delete( arr.at(3) );

Any access to this array element is formally an undefined behaviour by the c++ standard. Even assignment of NULL, like this:

对该数组元素的任何访问在形式上都是 C++ 标准的未定义行为。甚至分配NULL,像这样:

arr.at(3) = NULL;

2) If you really must use pointers, then use smart pointers (this specific case requires shared_ptr) :

2)如果你真的必须使用指针,那么使用智能指针(这个特定情况需要shared_ptr):

std::vector< std::shared_ptr< int > > arr;

回答by Srijan

cin>>n;
int array[n];
...
...
for(int k=0;k<n;k++){
array[k]=array[k+1];   //overwriting the current element of array with next element
array[n-1]=0;          //setting last element as 0
--n;                   //reducing the size of array
}
...
...