C++标准模板库(STL)——stack常见用法详解

  • stack的定义
stack<typename> name;
  • stack容器内元素的访问

  由于栈本身就是一种先进先出的数据结构,在STL中只能通过top()来访问栈顶元素。

示例:

 1 #include <iostream>
 2 #include <stack>
 3 using namespace std;
 4 stack<int> s;
 5 int main()
 6 {
 7     for(int i=0;i<5;i++){
 8         s.push(i+1);    //将i+1压入栈 
 9     }
10     cout<<s.top(); 
11     return 0;
12 }  
输出结果:
5
  • stack常用函数

  (1)push()

  push(x)将x入栈,时间复杂度为O(1)。

  (2)top()

  top()获得栈顶元素,时间复杂度为O(1)。

  (3)pop()

  pop()可以弹出栈顶元素,时间复杂度为O(1)。

示例:

 1 #include <iostream>
 2 #include <stack>
 3 using namespace std;
 4 stack<int> s;
 5 int main()
 6 {
 7     for(int i=0;i<5;i++){
 8         s.push(i+1);    //将i+1压入栈 
 9     }
10     for(int i=0;i<2;i++){
11         s.pop();    //连续两次将栈顶元素出栈(5,4) 
12     }
13     cout<<s.top(); 
14     return 0;
15 }   
输出结果:
3

  (4)empty()

  empty()可以检测stack内是否为空,返回true为空,返回false为非空,时间复杂度为O(1)。

示例:

 1 #include <iostream>
 2 #include <stack>
 3 using namespace std;
 4 stack<int> s;
 5 int main()
 6 {
 7     if(s.empty()==true){    //栈开始为空 
 8         cout<<"empty"<<endl;
 9     } 
10     else{
11         cout<<"not empty"<<endl;
12     }
13     s.push(1);        //入栈1后,栈非空 
14     if(s.empty()==true){
15         cout<<"empty"<<endl;
16     } 
17     else{
18         cout<<"not empty"<<endl;
19     }
20     return 0;
21 }  
输出结果:
empty
not empty

  (5)size()

  size()返回stack内元素的个数,时间复杂度为O(1)。

示例:

 1 #include <iostream>
 2 #include <stack>
 3 using namespace std;
 4 stack<int> s;
 5 int main()
 6 {
 7     for(int i=0;i<5;i++){
 8         s.push(i+1);    //将i+1入栈 
 9     } 
10     cout<<s.size(); 
11     return 0;
12 }    
输出结果:
5

 

posted @ 2021-06-10 16:41  熊猫耳朵  阅读(559)  评论(0编辑  收藏  举报