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

Deleting 1 element of dynamically allocated array?

#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;
}

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

您不能删除 c 类型数组中的特定元素。

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

您的一个解决方案是将索引保留在堆栈中的顶部项目,在每次推送后执行 index++,并在每次弹出索引后执行索引--。

请阅读 C 类型数组以及如何使用它们。

一些笔记 你应该为数组 class 之外的元素做输入。 调用 class 堆栈,因为数组是其他东西。