删除动态分配数组的 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;
}
该程序的目的是在动态分配的数组中添加和删除元素。虽然推送函数工作正常,但 pop 函数会导致编译器显示核心转储。(完整的错误太大,无法在此处发布(。我也尝试使用不带 [] 的删除运算符,但结果是一样的。请告诉我这个程序中的弹出功能有什么问题?
您无法删除 C 类型数组中的特定元素。
arr = new T[n];
delete[](arr + n - 1);
一种解决方案是将索引保留到堆栈中的顶部项目,在每次推送 do index++ 之后,以及在每个 pop 索引之后--.
请阅读有关 C 类型数组以及如何使用它们的信息。
一些注意事项您应该为 Array 类之外的元素进行输入。调用类 Stack,因为 Array 是别的东西。
相关文章:
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 使用动态分配的数组会导致代码分析发出虚假的C6386缓冲区溢出警告
- 在c++中使用动态分配的问题
- 访问动态分配列表中的元素
- 动态分配列表 - 创建一个函数,用于删除所有包含偶数值的元素
- c++ 使用动态分配运算符反向数组元素
- 我正在丢失动态分配的数组中的元素
- 通过动态分配插入列表元素
- 使用动态分配创建数组并将元素插入其中
- STL和元素插入中列表的动态分配
- 动态分配的结构阵列具有动态分配的结构阵列元素
- C++如何编写一个函数来检查元素是否存在于动态分配的数组中
- C++如何确定元素是否存在于动态分配的数组中
- 检查动态分配的数组C++中是否存在元素
- 循环访问映射并删除动态分配的元素
- 如何初始化vlaue,并将其逐个元素动态分配给数组
- 如何在不使用std::vectors的情况下,使用运算符==从动态分配的对象数组中删除元素
- 如何从动态分配的数组中删除元素
- 每次在std::list容器中插入元素时,都会执行动态分配
- 将元素推送到动态分配的指针数组int C++