C ++ STL pila :: arriba () con ejemplo : En este artículo, vamos a ver cómo class el elemento superior actual de una pila usando C STL ++ ?
Prototipo:
stack<T> st; //declaration
T st.top();
Parámetro:
No parameter passed
return escribir: T // tipo de datos
Archivo de cabecera que se incluirá:
#include <iostream>
#include <stack>
OR
#include <bits/stdc++.h>
Uso :
la función devuelve el elemento superior actual de una pila. (Sin cambio en el estado de pila)
Complejidad de tiempo: O (1)
Ejemplo:
For a stack of integer,
stack<int> st;
st.push(4);
st.push(5);
stack content:
5 <-- TOP
4
int temp=st.top() //5
Print temp // prints 5
stack content: //same as before, it don't change stack status
5 <-- TOP
4
C ++ aplicación:
#include <bits/stdc++.h>
using namespace std;
int main(){
cout<<"...use of top function...n";
int count=0;
stack<int> st; //declare the stack
st.push(4); //pushed 4
st.push(5); //pushed 5
st.push(6);
cout<<"stack elements are:n";
while(!st.empty()){//stack not empty
cout<<"top element is:"<<st.top()<<endl;//print top element
st.pop();
count++;
}
cout<<"stack emptyn";
cout<<count<<" pop operation performed total to make stack emptyn";
return 0;
}
salida
...use of top function...
stack elements are:
top element is:6
top element is:5
top element is:4
stack empty
3 pop operation performed total to make stack empty