关于C++中stack STL的问题
Questions about stack STL in C++
所以我想了解堆栈 STL 允许您做什么。我知道您首先包括堆栈,然后像这样创建一个对象:
#include<stack>
stack<int> calcStack;
但我想了解的是,既然我已经创建了一个堆栈,我该如何向其添加数字然后将它们读出。从视频中我看到有人简单地这样做:
calcStack.push(1); //Adding the number one to the top of the stack
calcStack.top(); //Reading the number at the top of the stack
calcStack.pop(); //Removing the number at the top of the stack
cout << calcstack.top << endl; //This should print out one
这是否意味着我可以只使用函数 .push() .top() .pop()
而无需在 .cpp 文件中定义它们?我还应该在头文件、实现文件或主文件 class?
中创建我的堆栈
这是我第一次使用堆栈,我刚刚开始使用 C++,所以任何指导将不胜感激!!!
您不必为堆栈定义任何函数。它是 标准库 的一部分。这意味着图书馆本身已经为您定义了它们。
您只需要担心:
- 包括正确的header
- linking 到正确的库(当你用 g++(而不是 gcc)编译时,标准库会自动 linked。如果你使用的是 MSVC,那么它也会自动link 在标准库中。
坦率地说,我在这里提到第 2 点的唯一原因是因为对于其他库,这是您需要做的事情。并且是 "linker errors".
的共同来源
所以我想了解堆栈 STL 允许您做什么。我知道您首先包括堆栈,然后像这样创建一个对象:
#include<stack>
stack<int> calcStack;
但我想了解的是,既然我已经创建了一个堆栈,我该如何向其添加数字然后将它们读出。从视频中我看到有人简单地这样做:
calcStack.push(1); //Adding the number one to the top of the stack
calcStack.top(); //Reading the number at the top of the stack
calcStack.pop(); //Removing the number at the top of the stack
cout << calcstack.top << endl; //This should print out one
这是否意味着我可以只使用函数 .push() .top() .pop()
而无需在 .cpp 文件中定义它们?我还应该在头文件、实现文件或主文件 class?
这是我第一次使用堆栈,我刚刚开始使用 C++,所以任何指导将不胜感激!!!
您不必为堆栈定义任何函数。它是 标准库 的一部分。这意味着图书馆本身已经为您定义了它们。
您只需要担心:
- 包括正确的header
- linking 到正确的库(当你用 g++(而不是 gcc)编译时,标准库会自动 linked。如果你使用的是 MSVC,那么它也会自动link 在标准库中。
坦率地说,我在这里提到第 2 点的唯一原因是因为对于其他库,这是您需要做的事情。并且是 "linker errors".
的共同来源