如果超出了堆栈的大小,如何自动调整它?c++
If the size of my stack is exceeded, how do I automatically adjust it? C++
所以我有一个使用LIFO(后进先出)方法的类CStack。使用标准变量bottom/top/size
和push/pop/full/empty/print
之类的方法。这是一个char
堆栈
我的问题是,如果我添加一些东西到这个堆栈,当它是满的,我怎么能自动调整大小?我想到了memcpy()
方法,但我真的不明白它是如何工作的(还)。
任何帮助都将不胜感激。
下面是我的代码:class CStack {
private:
char *bottom_;
char *top_;
int size_;
public:
CStack(int n = 20) {
bottom_ = new char[n];
top_ = bottom_;
size_ = n;
}
void push(char c) {
*top_ = c;
top_++;
}
int num_items() {
return (top_ - bottom_);
}
char pop() {
top_--;
return *top_;
}
int full() {
return (num_items() >= size_);
}
int empty() {
return (num_items() <= 0);
}
void print() {
cout << "Stack currently holds " << num_items() << " items: ";
for (char *element = bottom_; element < top_; element++) {
cout << " " << *element;
}
cout << "n";
}
~CStack() { // stacks when exiting functions
delete [] bottom_;
}
};
这应该是您想要的。它不处理异常但我猜你们在课程中还没学到这些?
void push(char c) {
int used = top - bottom;
if (used >= size_) {
// grow the stack
char* newBottom = new char[used + 20];
memcpy(newBottom, bottom_, used * sizeof(char));
top_ = newBottom + used;
size_ = used + 20;
delete[] bottom_;
bottom_ = newBottom;
}
*top_ = c;
top_++;
}
相关文章:
- 在Qt中自动调整小部件的大小
- 为什么 C++ 中的矢量不会自动调整大小
- win32 自动调整父窗口的大小以适合其内容
- 在内存(C 和/或 C++)中创建和管理字节缓冲区,该缓冲区可以根据需要自动调整大小
- 自动调整有关QlineDit中字体的自动调整
- 使用插入时自动调整标准::矢量的大小
- 在 OpenCV 中,设置曝光会导致我的网络摄像头软件无法自动调整曝光
- QlineEdit自动调整到内容大小
- QwtPlot在自动缩放期间自动调整大小
- Asio:是否有一个可自动调整大小的缓冲区来接收输入
- 矢量自动调整大小在多线程代码中是否是一种危险情况
- 如何使Qt网格布局自动调整列宽的大小
- QT QGraphicsScene 自动调整大小为原始图像大小
- 矢量是否自动调整大小
- 问题:如何在调整centralwidget的大小时使mainWindow自动调整大小
- 列的大小自动调整为QTableView的大小
- 如果子项调整大小,则让QWidget和QVBoxLayout自动调整大小(Qt4)
- QT 无法使用自动调整大小 QLineEdit & Layout
- 如何在VTK中自动调整渲染窗口的大小
- 当插入太多元素时,std::map是否自动调整大小