c++day6

整理思维导图

使用模板类,实现顺序栈

cpp 复制代码
#include <iostream>
using namespace std;

template <typename T>
class SeqStack {
public:
    SeqStack(int size = 10);
    ~SeqStack();
    bool push(const T& data);
    bool pop(T& data);
    bool getTop(T& data) const;
    bool isEmpty() const;
    bool isFull() const;

private:
    T* m_pBuffer;
    int m_iSize;
    int m_iTop;
};

template <typename T>
SeqStack<T>::SeqStack(int size) {
    m_iSize = size;
    m_iTop = -1;
    m_pBuffer = new T[m_iSize];
}

template <typename T>
SeqStack<T>::~SeqStack() {
    delete[] m_pBuffer;
}

template <typename T>
bool SeqStack<T>::push(const T& data) {
    if (isFull()) {
        return false;
    }
    m_pBuffer[++m_iTop] = data;
    return true;
}

template <typename T>
bool SeqStack<T>::pop(T& data) {
    if (isEmpty()) {
        return false;
    }
    data = m_pBuffer[m_iTop--];
    return true;
}

template <typename T>
bool SeqStack<T>::getTop(T& data) const {
    if (isEmpty()) {
        return false;
    }
    data = m_pBuffer[m_iTop];
    return true;
}

template <typename T>
bool SeqStack<T>::isEmpty() const {
    return m_iTop == -1;
}

template <typename T>
bool SeqStack<T>::isFull() const {
    return m_iTop == m_iSize - 1;
}

int main() {
    SeqStack<int> stack;
    stack.push(1);
    stack.push(2);
    stack.push(3);

    int top;
    stack.getTop(top);
    cout << "栈顶元素为:" << top << endl;

    int data;
    stack.pop(data);
    cout << "弹出的元素为:" << data << endl;

    stack.getTop(top);
    cout << "新的栈顶元素为:" << top << endl;

    return 0;
}

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

cpp 复制代码
#include <iostream>
using namespace std;
void fun(char *p)
{
    int i=0;
    while (1) {
        cout<<*(p+i);
        i++;
        if(i>9){
           throw char();
        }
    }
}
int main()
{
    char arr[10]="blackpink";
    try {
        fun(arr);
    } catch (char) {
        cout<<"数组越界"<<endl;
    }
    return 0;
}
相关推荐
yiangL_4 小时前
课后作业4:基于 Python 的古诗词词云可视化(P205)
开发语言·python
JosieBook5 小时前
【鸿蒙开源】把 Windows 任务栏上的流量表搬到鸿蒙 PC:TrafficMonitor 1.86 的 C++ 内核移植实践
c++·windows·harmonyos
Huangjin007_6 小时前
【C++ 算法竞赛篇】STL 常用知识点速通指南
c++·算法
geovindu6 小时前
rust: Functional Options Pattern
开发语言·后端·设计模式·rust·函数式选项模式·惯用法型模式
skywalk81637 小时前
把「假成功」赶出工具层:lightharness 两天升级复盘(4×5 模式矩阵 + 工具层 5 个缺陷)
开发语言·前端·人工智能·lightharness
敲上瘾8 小时前
Qt控件通用属性:geometry、qrc资源到QSS样式表等
开发语言·c++·qt·ui
炸膛坦客8 小时前
单片机/C/C++八股:(三十三)取别名
c语言·c++·单片机
听情歌落俗9 小时前
嵌入式学习1-C语言基础语法与STM32实践
c语言·开发语言
小飞在努力9 小时前
【实现负载均匀在线判题⑤】MVC 架构搭建与 Model 题目数据模块实现
c语言·开发语言·c++·笔记·后端
ShineWinsu9 小时前
对于Qt:QFontDialog的解析
c++·qt·面试·gui·字体·客户端·qfontdialog