关于c++中的STL中的栈stack的使用

来源:互联网 发布:js链表 编辑:程序博客网 时间:2024/05/21 01:29

1.首先,STL库是c++特有的,c语言是没有的,因为c语言不支持模板和泛型,不支持类,所以只能在c++中使用STL中的栈stack。

2.先引入栈stack:

#include<stack>


3.声明和初始化一个栈:

stack<double> numbers;//这里使用了泛型,也就是c++中的类模板,不多解释!

4.进栈操作:

numbers.push(2.3456);

5.出栈操作:

numbers.pop();//栈的数据结构是last in first out(后进先出),所以就可以直接出栈numbers.pop().


6.例子:

==========使用STL中的栈进行序列的反转,请修改好下面代码中的语法错误,编译运行==========

#include <stack>

int main( )

/* Pre: The user supplies an integer n andn decimal numbers.

Post: The numbers are printed in reverseorder.

Uses: The STL class stack and its methods*/

{

int n;

double item;

stack<double> numbers; // declaresand initializes a stack of numbers

cout << " Type in an integer nfollowed by n decimal numbers."

<< endl

<< " The numbers will be printedin reverse order."

<< endl;

cin >> n;

for (int i = 0; i < n; iCC) {

cin >> item;

numbers.push(item);

}

cout << endl << endl;

while (!numbers.empty( )) {

cout << numbers.top( ) <<" ";

numbers.pop( );

}

cout << endl;

}