Implementing Pairs in STL with Vectors

Beginner

Introduction

In this tutorial, we will learn how to implement the Pair Template in C++ using a Vector in the STL library. Specifically, we will cover how to:

Declare a Vector and Fill it with Pairs of Integers

The first step in implementing the Pair Template in C++ is to declare an empty vector of pairs and insert pairs of integers into it.

#include <iostream>
#include <bits/stdc++.h>

using namespace std;

int main()
{
    //create an empty vector of pair
    vector<pair<int, int>> v;

    //insert elements into the vector
    v.push_back(make_pair(8, 64));
    v.push_back(make_pair(1, 1));
    v.push_back(make_pair(3, 6));
    v.push_back(make_pair(2, 4));
    v.push_back(make_pair(5, 25));

    return 0;
}

Print the Vector of Pairs

Next, we will print the vector of pairs to the console. We can access the pair elements using the first and second attributes.

cout << "Printing the Vector of Pairs: \n";

int n = v.size();

for (int i = 0; i < n; i++)
{
    cout << "\nSquare of " << v[i].first << " is " << v[i].second; //accessing the pair elements
}

Sort the Vector in Ascending Order

Lastly, we will sort the vector in ascending order using the sort function from the STL library. By default, it sorts on the basis of the first element of the pair.

//Sorting the vector in ascending order - by default on the basis of first element of the pair
sort(v.begin(), v.end());

cout << "\n\n\n\nThe elements of the Vector after Sorting are:\n ";

//prining the Sorted vector
for (int i = 0; i < n; i++)
{
    cout << "\nSquare of " << v[i].first << " is " << v[i].second; // accessing the pair elements
}

Summary

In this tutorial, we learned how to implement Pairs in STL with Vectors in C++. We covered declaring an empty vector of pairs, filling it with pairs of integers, printing the vector of pairs, and sorting the vector in ascending order. By following along with the code examples above, you can start utilizing the Pair Template to make your C++ code more efficient and effective.

Other Tutorials you may like