删除动态分配数组的 1 个元素

Deleting 1 element of dynamically allocated array?

本文关键字:元素 动态分配 数组 删除      更新时间:2023-10-16
#include<iostream>
using namespace std;
template <class T>
class Array{
    T *arr; int n,val,count;
public:
    Array(int a):n(a){
        arr=new T[n];
        val=n-1; count=0;
    }
    void push(){
        if(count>=n){
            throw "Overflow. Array size limit exceeded";}
        else{
            int i; T num;
            cout<<"Enter no.: ";
            cin>>num;
            if(cin.fail()){
                cout<<"Wrong data type"<<endl;}
            else{
                for(i=0;i<n;i++){
                    *(arr+i+1)=*(arr+i);}
                *arr=num; count++;
            }
        }
    }
    void pop(){
        if(val<=0){
            throw "Underflow. Array limit has been exhausted";}
        else{
            delete[] (arr+n-1);
            val--; n-=1;
        }
    }
};
int main(){
    int x,n;
    cout<<"Enter size of an array: ";
    cin>>n;
    Array <int>a(n);
    do{
        try{
            cout<<"Enter 1 to push,2 for pop and 0 to exit: ";
            cin>>x;
            if(x==1){
                a.push();}
            else if(x==2){
                a.pop();}
            }
        catch(const char* e){
            cerr<<e<<endl;}
        catch(int a){
            cout<<"Wrong data type";}
    }while(x!=0);

   return 0;
}

该程序的目的是在动态分配的数组中添加和删除元素。虽然推送函数工作正常,但 pop 函数会导致编译器显示核心转储。(完整的错误太大,无法在此处发布(。我也尝试使用不带 [] 的删除运算符,但结果是一样的。请告诉我这个程序中的弹出功能有什么问题?

您无法删除 C 类型数组中的特定元素。

arr = new T[n];
delete[](arr + n - 1);

一种解决方案是将索引保留到堆栈中的顶部项目,在每次推送 do index++ 之后,以及在每个 pop 索引之后--.

请阅读有关 C 类型数组以及如何使用它们的信息。

一些注意事项您应该为 Array 类之外的元素进行输入。调用类 Stack,因为 Array 是别的东西。