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;
}
相关推荐
saltymilk13 小时前
C++ 模板参数推导问题小记(模板类的模板构造函数)
c++·模板元编程
感哥13 小时前
C++ lambda 匿名函数
c++
沐怡旸19 小时前
【底层机制】std::unique_ptr 解决的痛点?是什么?如何实现?怎么正确使用?
c++·面试
感哥19 小时前
C++ 内存管理
c++
博笙困了1 天前
AcWing学习——双指针算法
c++·算法
感哥1 天前
C++ 指针和引用
c++
感哥2 天前
C++ 多态
c++
沐怡旸2 天前
【底层机制】std::string 解决的痛点?是什么?怎么实现的?怎么正确用?
c++·面试
River4162 天前
Javer 学 c++(十三):引用篇
c++·后端
感哥2 天前
C++ std::set
c++