C++ 2024-4-2 作业

1.模板类实现顺序栈

cpp 复制代码
#include <iostream>
#define MAX 8
using namespace std;
template<typename T>
class stack
{
    T data[MAX];
    int top;
public:
    stack():top(-1){}
    bool empty_stack();
    bool full_stack();
    void push_stack(T data);
    void pop_stack();
    void show();
};

template<typename T>
bool stack<T>::empty_stack()
{
    return top == -1;
}

template<typename T>
bool stack<T>::full_stack()
{
    return top == MAX-1;
}

template<typename T>
void stack<T>::push_stack(T data)
{
    if(full_stack())
    {
        return;
    }
    top++;
    this->data[top] = data;
    return;
}

template<typename T>
void stack<T>::pop_stack()
{
    if(empty_stack())
    {
        cout<<"栈为空"<<endl;
        return;
    }
    cout<<"出栈的元素为"<<data[top]<<endl;
    top--;
    return;
}

template<typename T>
void stack<T>::show()
{
    if(empty_stack())
    {
        cout<<"栈为空"<<endl;
        return;
    }
    for(int i=0;i<=top;i++)
    {
        cout<<data[i];
    }
    cout<<endl;
}

int main()
{
    stack<int>s1;
    s1.push_stack(1);
    s1.push_stack(2);
    s1.push_stack(3);
    s1.push_stack(4);
    s1.push_stack(5);
    s1.push_stack(6);
    s1.push_stack(7);
    s1.push_stack(8);
    s1.show();
    s1.pop_stack();
    s1.show();
    cout<<s1.full_stack()<<endl;
    return 0;
}

2. char类型的字符数组,实现对数组越界的抛出异常并处理

cpp 复制代码
#include <iostream>
#include <cstring>
using namespace std;
void arr_size(const char *p,int size)
{
    int len = strlen(p);//5
    if(size>=len)
    {
        throw int(0);
    }
}
int main()
{
    char arr[6] = "hello";
    int size = 4;
    int size2 = 8;
    try
    {
        arr_size(arr,size);

    } catch (int ret)
    {
        if(ret==0)
        {
            cout<<"数组越界"<<endl;
        }
    }

    try
    {
        arr_size(arr,size2);

    } catch (int ret)
    {
        if(ret==0)
        {
            cout<<"数组越界"<<endl;
        }
    }
    cout<<arr[size]<<endl;
    cout<<arr[size2]<<endl;

    return 0;
}
相关推荐
浅念-2 小时前
Linux 开发环境与工具链
linux·运维·服务器·数据结构·c++·经验分享
旺仔.2913 小时前
容器适配器:stack栈 、queue队列、priority queue优先级队列、bitset位图 详解
c++
潜创微科技--高清音视频芯片方案开发4 小时前
2026年C转DP芯片方案深度分析:从适配场景到成本性能的优选指南
c语言·开发语言
Thomas.Sir4 小时前
第三章:Python3 之 字符串
开发语言·python·字符串·string
刘景贤4 小时前
C/C++开发环境
开发语言·c++
Dxy12393102165 小时前
Python 根据列表中某字段排序:从基础到进阶
开发语言·windows·python
Zero5 小时前
机器学习微积分--(1)核心思想
人工智能·算法·机器学习
competes5 小时前
学生需求 交易累计积分,积分兑换奖品
java·大数据·开发语言·人工智能·java-ee
splage6 小时前
Java进阶——IO 流
java·开发语言·python