Open In App

make_pair() in C++ STL

Last Updated : 19 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In C++, make_pair() is a standard library function used to construct a key-value pair from the given arguments. The type of the pair constructed is deduced automatically from the type of arguments. In this article, we will learn about make_pair() function in C++.

Let’s take a quick look at a simple example that illustrates std::make_pair():

C++
#include <bits/stdc++.h>
using namespace std;
int main() {

    // Creating a pair
    auto p = make_pair('A', 11);

    cout << p.first << " " << p.second;
  
    return 0;
}

Output
A 11

This article covers the syntax, usage, and common examples of make_pair() function in C++:

Syntax of make_pair()

The make_pair() function defined inside <utility> header file.

make_pair(key, val);

Parameters

  • key: Represents the key for the pair object i.e. first value.
  • val: Represents the value for the pair object i.e. second value.

Return Value

  • Returns an object of std::pair having first and second members as key and val that were passed.

Examples of make_pair()

The following examples demonstrates the use of make_pair() function in different scenarios and for different purposes:

Creating a Pair of Integers

C++
#include <bits/stdc++.h>
using namespace std;

int main() {
  
    // Creating a pair of integers
    pair<int, int> p = make_pair(10, 20);

    cout << p.first << ": " << p.second;

    return 0;
}

Output
10: 20

Creating Pair of Integer and String

C++
#include <bits/stdc++.h>
using namespace std;

int main() {

    // Make pair of integer and string
    auto p1 = make_pair(1, "Geeks");

    cout << p1.first << ": " << p1.second;
    return 0;
}

Output
1: Geeks

Inserting Pairs in a Map

C++
#include <bits/stdc++.h>
using namespace std;

int main() {
    map<int, string> m;

    // Inserting pairs into the map
    m.insert(make_pair(1, "Geeks"));
    m.insert(make_pair(2, "Gfg"));

    for (const auto& pair : m) {
        cout << pair.first << ": " << pair.second
          << endl;
    }

    return 0;
}

Output
Alice Geeks
Bob Geeks for Geeks

Article Tags :
Practice Tags :

Similar Reads