【发布时间】:2018-04-16 01:19:44
【问题描述】:
我正在尝试根据用户输入的字母数动态分配堆栈。
我当前的程序获取一组字母或数字,然后按 FILO 顺序输出它们(因此顺序相反)。
例如,如果用户输入 123,它将堆栈的大小设置为 3,并返回 321。
这是我的标题(类)
class CharStack {
enum {size = 100}; //size of stack. big enough to receive long letters.
int top; //top pointer
char buf[size]; //stack's size
public:
CharStack() //constructor
{top = size;}
bool chkEmpty() const //true if no data in stack
{return top == size;}
bool chkFull() const //true if stack is full
{return !top;}
bool push(char ch); //pop data from stack
char pop();
};
这是我的主要任务。
int main() {
CharStack chStack; //A stack with 100
char str[100];
int *size;
cout << "input letter or numbers:";
cin >> str;
size = new int[strlen(str)+1]; //count number of letters.
等等……
我想我需要做的就是设置size (in main) = buf[size](在头文件中)。我相信有一个非常简单的方法可以解决这个问题,但我就是看不到。
【问题讨论】:
-
FIFO 意味着元素按照它们进入的顺序出现,而不是颠倒。无论如何,要回答您的问题,
size是CharStack的private成员,因此您的代码中的main()无法访问。如果您需要访问私有值,请声明返回它的类的public成员函数。 -
FIFO:先进先出,不会恢复。
-
你知道std::stack吗?
-
感谢所有 cmets。我刚刚将 FIFO 编辑为 FILO。我将在 std::stack 上进行谷歌搜索。
-
FILO 命名为 LIFO。
标签: c++ stack dynamic-memory-allocation