Stack of pair in C++ STL

Hello folks! This article is aimed at understanding the Stack of Pair in C++. So, before moving to topics let’s have a recap of Stacks and Pairs in C++.

Stack

The stack is a type of Data Structure used of store and process elements. It follows LIFO(Last in First out) or FILO(First in Last out) order to insert and remove elements. You can store any type of data in Stack such as int, string, pairs, char, etc. Their are various methods associated with Stack such as push(), pop(), top(), emplace(), empty(), size(), etc.

For more information on stack: Stack in C++ Standard Template Library (STL)

Pair

Pair is a container in C++. You can use is by importing <utility> function. There are 2 elements in Pair of any type such as int or char. There are several methods or template functions of pairs such as make_pair() and swap().

For more information on pairs visit – Pair in STL ( Standard Template Library ) in C++

Stack of Pair in C++

We can use this in various places for solving complex Data Structures problems.

       Syntax:

   stack<pair<datatype, datatype>> stack;

Example code based on the implementation of Stack in C++:

#include <bits/stdc++.h> 
using namespace std; 
void print(pair<int, int> p) 
{ 
  
    cout << "("
         << p.first << ", "
         << p.second << ") "; 
} 
  
void Showstack(stack<pair<int, int> > s) 
{ 
    while (!s.empty()) { 
        printPair(s.top()); 
        s.pop(); 
    } 
  
    cout << '\n'; 
} 
  
int main() 
{ 
    stack<pair<int, int> > s;  
    s.push({ 15, 5 }); 
    s.push({ 1, 5 }); 
    s.push({ 5, 10 }); 

  
    cout << "Stack of Pairs: "; 
    Showstack(s); 
  
    cout << "\nSize of Stack: "
         << s.size(); 
    cout << "\nTop of Stack: "; 
    printPair(s.top()); 
  
    cout << "\n\nRemoving \n"; 
    s.pop(); 
  
    cout << "Current Stack of Pairs: "; 
    Showstack(s); 
  
    return 0; 
}

Output:

Stack of Pairs:  (5, 10) (1, 5) (15, 5) 

Size of Stack: 3
Top of Stack: (5, 10) 

Removing the pair
Current Stack of Pairs: (1, 5) (15, 5)

In this code we are making a stack of pairs using stack<pair> syntax then we are inserting elements in the pair and then inserting that pair into a stack using s.push(). You can also remove the element on-screen using an s.pop() syntax function. At the end printed the output on the screen using cout. I hope you enjoyed this article.

Leave a Reply

Your email address will not be published. Required fields are marked *