整理思维导图



使用模板类,实现顺序栈
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;
}