【发布时间】:2014-07-08 01:05:33
【问题描述】:
所以我有一个使用 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_;
}
};
【问题讨论】:
-
如果你想在内存中保持所有元素连续,你必须分配一个新的更大的数组,复制旧的,然后删除原来的。
-
但请注意,您的代码不是惯用的 C++:
new char[n]创建了一个由n元素组成的数组,但您真正想要的是一个带有 的 empty 堆栈没有 元素。是时候将内存与对象分开了。 -
所以我不能这样做?
-
@KerrekSB 没关系;
vector.reserve()做了类似的事情。 -
@MattMcNabb:
reserve()在不创建对象的情况下获取内存...从某种意义上说,详细研究std::vector<int>可以教会您大约 95% 的 C++... :-)
标签: c++ automation stack stack-overflow stack-size