4.2C++

写一个char类型的字符数组,对该数组访问越界时抛出异常,并做处理。

#include <iostream>

using namespace std;
void fun(char (&a)[10],int i)
{
    if(i>=10)
    {
        throw int();
    }
    else if(a==NULL){
        throw double();
    }
    cout<<"访问了第"<<i<<"位为:"<<a[i]<<endl;
}
int main()
{
    char a[10]="hello sed";
    int i=0;
    cout<<"输入访问位:"<<endl;
    cin>>i;
    try {
        fun(a,i);
    } catch (int) {
        cout<<"数组访问越界"<<endl;
    }
    catch (double)
    {
        cout<<"入参为空,请检查"<<endl;
    }
    return 0;
}

使用模板类,实现顺序栈

#include <iostream>
using namespace std;
template <typename T>
class Stack
{
private:
    T* data;
    int top;
    int size;
public:
    Stack(int size);
    //构造函数
    ~Stack();
    void Clear();
    //清空栈
    bool Empty();
    //判空
    bool Full()
    {
        return top==size-1;
    }
    //判满
    void Push(T elem);
    //入栈
    void Pop();
    //出栈
    void show()
    {
        for(int i=0;i<=top;i++)
        {
            cout << data[i] << "->";
        }
        cout << endl;
    }
    //查看
};
template <typename T>
Stack<T>::Stack(int size):size(size)
{
    data = new T[size];
    if (data == NULL)
    {
        exit(1);
    }
    top=-1;
}
template <typename T>
Stack<T>::~Stack()
{
    cout<<"S的析构"<<endl;
    delete[] data;
}
template <typename T>
void Stack<T>::Clear()
{
    if(Empty())
    {
        return;
    }
    top=-1;
}
template <typename T>
bool Stack<T>::Empty()
{
    return top==-1;
}
template <typename T>
void Stack<T>::Push(T e)
{
    if (Full())
    {
        return;
    }
    top++;
    data[top]=e;
}
template <typename T>
void Stack<T>::Pop()
{
    if (Empty())
    {
        cout << "栈为空" << endl;
        return;
    }
    cout << "出栈的元素为:" << data[top--] << endl;
}
int main()
{

    Stack <int>s1(5);
    for(int i=0;i<5;i++)
    {
        int n;
        cout<<"输入栈值:"<<endl;
        cin>>n;
        s1.Push(n);
    }
    s1.show();
    cout << "---------------" << endl;
    for(int i=0;i<5;i++)
    {
        s1.Pop();
        s1.show();
        cout << "---------------" << endl;
    }
    s1.Clear();
    s1.show();
    return 0;
}

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值