1stack<int> stk;
2stk.push(5);
3int ans = stk.top(5); // ans =5
4stk.pop();//removes 5
1#include <iostream>
2using namespace std;
3int stack[100], n=100, top=-1;
4void push(int val) {
5 if(top>=n-1)
6 cout<<"Stack Overflow"<<endl;
7 else {
8 top++;
9 stack[top]=val;
10 }
11}
12void pop() {
13 if(top<=-1)
14 cout<<"Stack Underflow"<<endl;
15 else {
16 cout<<"The popped element is "<< stack[top] <<endl;
17 top--;
18 }
19}
20void display() {
21 if(top>=0) {
22 cout<<"Stack elements are:";
23 for(int i=top; i>=0; i--)
24 cout<<stack[i]<<" ";
25 cout<<endl;
26 } else
27 cout<<"Stack is empty";
28}
29int main() {
30 int ch, val;
31 cout<<"1) Push in stack"<<endl;
32 cout<<"2) Pop from stack"<<endl;
33 cout<<"3) Display stack"<<endl;
34 cout<<"4) Exit"<<endl;
35 do {
36 cout<<"Enter choice: "<<endl;
37 cin>>ch;
38 switch(ch) {
39 case 1: {
40 cout<<"Enter value to be pushed:"<<endl;
41 cin>>val;
42 push(val);
43 break;
44 }
45 case 2: {
46 pop();
47 break;
48 }
49 case 3: {
50 display();
51 break;
52 }
53 case 4: {
54 cout<<"Exit"<<endl;
55 break;
56 }
57 default: {
58 cout<<"Invalid Choice"<<endl;
59 }
60 }
61 }while(ch!=4);
62 return 0;
63}
1/* Stack is a data structure that provides two O(1) time operations:
2adding an element to the top and removing an element from the top.
3It is only possible to access the top element of a stack. */
4stack<int> s;
5s.push(3);
6s.push(2);
7s.push(5);
8cout << s.top(); // 5
9s.pop();
10cout << s.top(); // 2
1// Fast DIY Stack
2template<class S, const int N> class Stack {
3private:
4 S arr[N];
5 int top_i;
6
7public:
8 Stack() : arr(), top_i(-1) {}
9 void push (S n) {
10 arr[++top_i] = n;
11 }
12 void pop() {
13 top_i--;
14 }
15 S top() {
16 return arr[top_i];
17 }
18 S bottom() {
19 return arr[0];
20 }
21 int size() {
22 return top_i+1;
23 }
24};
1#include <bits/stdc++.h>
2
3stack<int> stk;
4stk.push(5);
5int ans = stk.top(5); // ans =5
6stk.pop();//removes 5
1#take input 2D vector
2
3vector<vector<int> > v;
4for(int i=0;i<n;i++){
5for(int j=0;j<m;j++){
6v[i].push_back(data);
7}}