4.2C++

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

cpp 复制代码
#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;
}

使用模板类,实现顺序栈

cpp 复制代码
#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;
}
相关推荐
老四啊laosi4 小时前
[C++进阶] 24. 哈希表封装unordered_map && unordered_set
c++·哈希表·封装·unordered_map·unordered_set
妙为5 小时前
银河麒麟V4下编译Qt5.12.12源码
c++·qt·国产化·osg3.6.5·osgearth3.2·银河麒麟v4
史迪仔01128 小时前
[QML] QML IMage图像处理
开发语言·前端·javascript·c++·qt
会编程的土豆9 小时前
【数据结构与算法】再次全面了解LCS底层
开发语言·数据结构·c++·算法
低频电磁之道9 小时前
解决 Windows C++ DLL 导出类不可见的编译错误
c++·windows
君义_noip11 小时前
信息学奥赛一本通 4150:【GESP2509七级】⾦币收集 | 洛谷 P14078 [GESP202509 七级] 金币收集
c++·算法·gesp·信息学奥赛·csp-s
Ricky_Theseus11 小时前
静态链接与动态链接
c++
澈20712 小时前
双指针,数组去重
c++·算法
小辉同志12 小时前
207. 课程表
c++·算法·力扣·图论
feng_you_ying_li12 小时前
C++11,{}的初始化情况与左右值及其引用
开发语言·数据结构·c++