How to use Pair in C++ STL (Standard Template Library)

Filed Under: C++
Stl Pair Cpp

In this article, we’ll take a look at using pair in C++ Standard Template Library (STL).

This is quite a useful container, which serves to reduce the pain of working with a single return type.

Similar to a tuple in Python, the std::pair template class is the C++ way of having multiple objects in one variable.

Let’s look at how we can use this, use some illustrative examples!


Basic Syntax of std::pair

This is in the std namespace, so we need to prefix the namespace name before using it.

This is a template class, and can take templated arguments, based on the type.

template <class T1, class T2> struct pair;

To declare a pair variable called my_pair, the syntax is as follows:

std::pair<typename T1, typename T2> my_pair;

Here, T1 and T2 can be of any type, such as int, char, string, etc.

Now that we have our pair variable declared, let’s now define it.

A pair has two elements, called first and second.

  • To get/set the first element, use my_pair.first.
  • To get/set the second element, use my_pair.second.

The elements must be of the appropriate type which conforms to T1 and T2, in the declaration.

Let’s now assign the pair elements to specific values.

We’ll construct a pair of std::pair<int, char>, and assign it to 2 values accordingly.

#include <iostream>

int main() {

    // Define my_pair
    std::pair<int, char> my_pair;

    // Now assign the first element to an integer
    my_pair.first = 10;

    // And the second element to a character
    my_pair.second = 'H';

    std::cout << "First element : " << my_pair.first << std::endl;
    std::cout << "Second element : " << my_pair.second << std::endl;
    return 0;
}

Output

First element : 10
Second element : H

As you can observe, we can easily manipulate the pair elements!


Initializing a Pair in C++ STL

We can also directly initialize a pair variable, using it’s constructor!

Look at the below example, which directly constructs a pair.

Here, I have used the auto keyword, which is very useful for automatic type inference!

We don’t need to write the huge std::pair<> again and again!

#include <iostream>
#include <string>

int main() {
    // Initialize a pair directly!
    auto my_pair = std::pair<int, std::string>(1, "Hello");

    std::cout << "First element : " << my_pair.first << std::endl;
    std::cout << "Second element : " << my_pair.second << std::endl;
    return 0;
}

Output

First element : 1
Second element : Hello

Indeed, we were able to directly initialize the pair variable.

Concise initialization using std::make_pair()

Another way of initializing a pair is to use the std::make_pair(T1 a, T2 b) function.

The advantage to this way is that we do have not to explicitly have to specify the types!

This makes writing short and concise code more easier! Look at the same example above, now rewritten using std::make_pair().

#include <iostream>
#include <string>

int main() {
    auto my_pair = std::make_pair(1, "Hello");

    std::cout << "First element : " << my_pair.first << std::endl;
    std::cout << "Second element : " << my_pair.second << std::endl;
    return 0;
}

I never once mentioned the type name here. auto and make_pair() did this work for us!

First element : 1
Second element : Hello

Let’s now look at some other things that we can do with this container class!

Default Operators for std::pair

We’ll look at how we can compare two std::pair variables using logical operators.

  • If we want to assign a pair to another pair variable, using =, the first value of the first pair is assigned to the first value of the second pair. (Same for second element)
  • The != operator compares the first and second elements, and returns True only if any one of them are not equal.
  • Similarly, the == operator also does a corresponding comparison.
  • The <= and >= operators first check the first two elements of both pairs, and return the comparison. If they are equal, the second elements are compared.

To illustrate all these operators, a simple example may be easy to visualize.

#include <iostream> 
  
int main() 
{ 
    std::pair<int, int>pair1 = make_pair(10, 12); 
    std::pair<int, int>pair2 = make_pair(10, 14); 
  
    std::cout << (pair1 == pair2) << std::endl; 
    std::cout << (pair1 != pair2) << std::endl; 
    std::cout << (pair1 >= pair2) << std::endl; 
    std::cout << (pair1 <= pair2) << std::endl; 
  
    return 0; 
} 

Output

0
1
0
1

Operator Overloading with std::pair

We can overload certain specific operators directly, on std::pair.

The below operators can be overloaded in C++20.

  • Operator ==
  • Operator <=>

PLEASE NOTE: All the logical operators except == CANNOT be overloaded in C++20. This is a major change as compared to C++17.

Let’s take an example of overloading the logical equals operator (==).

We’ll overload this to compare values of a pair. To be equal, both the first and second values must match.

template <typename T1, typename T2>
bool operator== (std::pair <T1, T2> &p, std::pair <T1, T2> &q) {
    if (p.first == q.first && p.second == q.second) {
        std::cout << "Equal\n";
        return true;
    }
    std::cout << "Not Equal\n";
    return false;
}

The complete code is shown below:

#include <iostream>
#include <string>

template <typename T1, typename T2>
bool operator== (std::pair <T1, T2> &p, std::pair <T1, T2> &q) {
    if (p.first == q.first && p.second == q.second) {
        std::cout << "Equal\n";
        return true;
    }
    std::cout << "Not Equal\n";
    return false;
}

int main() {
    auto p = std::make_pair(1, "Hello");
    auto q = std::make_pair(1, "Hello");

    if (p == q) {
        printf("True\n");
    }
    else {
        printf("False\n");
    }

    auto r = std::make_pair(1, "Hello");
    auto s = std::make_pair(1, "JournalDev");

    if (r == s) {
        printf("True\n");
    }
    else {
        printf("False\n");
    }
    return 0;
}

Output

Equal
True
Not Equal
False

As you can see, we have indeed overloaded the == operator to make this work for std::pair as well!


Conclusion

In this article, we learned how we could use the pair container class in C++ STL. We also saw how we could use different operators on two sets of pairs.

References


Leave a Reply

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

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages