Open In App

How to Create a Stack of Pairs in C++?

Last Updated : 06 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In C++, Stacks are a type of container adaptor with LIFO(Last In First Out) type of working, where a new element is added at one end (top) and an element is removed from that end only. A pair is a simple container that stores data in a key and value format. In this article, we will learn how to create a stack of pairs in C++.

Example

Input:
myPair1 = {1, “C++”};
myPair2 = {2, “Java”};

Output:
myStack = [ {1, “C++”},
            {2, “Java”} ]

Stack of Pairs in C++

To create a stack of pairs in C++, we will pass the template parameter in the stack declaration as a pair. This will create a stack where each element is a pair.

Syntax to Declare Stack of Multiset

stack <pair <keyType, valueType>> myStack;

C++ Program to Create a Stack of Pairs

The below example demonstrates how we can create a stack of pairs in C++.

C++




// C++ Program to illustrate how to create a stack of pairs
#include <iostream>
#include <stack>
#include <utility>
using namespace std;
  
int main()
{
    // Initialize two pairs
    pair<int, string> myPair1 = make_pair(1, "C++");
    pair<int, string> myPair2 = make_pair(2, "Java");
  
    // Create a stack of pairs
    stack<pair<int, string> > myStack;
    myStack.push(myPair1);
    myStack.push(myPair2);
  
    // Print the stack of pairs
    while (!myStack.empty()) {
        pair<int, string> topPair = myStack.top();
        myStack.pop();
        cout << "{" << topPair.first << ", "
             << topPair.second << "}, ";
    }
    cout << endl;
  
    return 0;
}


Output

{2, Java}, {1, C++}, 

Time Complexity: O(N), where N is the number of pairs.
Auxiliary Space: O(N)


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads