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;
}
相关推荐
kk哥889932 分钟前
C++ 对象 核心介绍
java·jvm·c++
helloworddm33 分钟前
WinUI3 主线程不要执行耗时操作的原因
c++
无能者狂怒1 小时前
YOLO C++ Onnx Opencv项目配置指南
c++·opencv·yolo
集智飞行2 小时前
c++函数传参的几种推荐方式
开发语言·c++
点云SLAM3 小时前
C++ Template(模板)解读和模板报错如何“逆向阅读”定位
c++·c++20·c++模版·c++高级应用·c++模版报错定位
明洞日记3 小时前
【数据结构手册008】STL容器完全参考指南
开发语言·数据结构·c++
农夫山泉2号4 小时前
【c++】——c++编译的so中函数有额外的字符
java·服务器·c++
仰泳的熊猫5 小时前
1077 Kuchiguse
数据结构·c++·算法·pat考试
WolfGang0073216 小时前
代码随想录算法训练营Day48 | 108.冗余连接、109.冗余连接II
数据结构·c++·算法
崇山峻岭之间7 小时前
C++ Prime Plus 学习笔记041
c++·笔记·学习