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;
}
相关推荐
郝学胜-神的一滴6 小时前
Qt 高级开发 009: C++ Lambda 表达式
开发语言·c++·qt·软件构建
石山代码7 小时前
C++ 轻量级日志系统
开发语言·c++
王老师青少年编程9 小时前
2026年全国青少年信息素养大赛初赛真题(算法应用主题赛C++初中组初赛真题3:文末附答案和解析)
c++·真题·答案·初赛·2026年·青少年信息素养大赛·初中组
轻颂呀10 小时前
C++11——并发库介绍
开发语言·c++
梓䈑11 小时前
【算法题攻略】快速排序 和 归并排序
数据结构·c++·排序算法
fan_music12 小时前
设计模式学习
c++·设计模式
小小编程路12 小时前
C++ 常用逻辑运算符
开发语言·c++·算法
‎ദ്ദിᵔ.˛.ᵔ₎14 小时前
C++ 智能指针
开发语言·c++
Lumbrologist14 小时前
【C++】零基础入门 · 第 4 节:循环结构(while、for、do-while)
开发语言·c++
我命由我1234515 小时前
Android Framework P4 - ServiceManager 进程
android·c语言·c++·visualstudio·android studio·android-studio·android runtime