Understanding the Pair

Understanding pair in C++

What is pair?

pair is a simple container defined in the C++ Standard Library to store a pair of values. The values can be of different types, and the pair provides a convenient way to return two values from a function or to store two related values together.

Why Use pair?

  • Convenience: Easily group two values together.

  • Flexibility: Values can be of different types.

  • Simplicity: Provides an easy way to return multiple values from a function.

Syntax

Here's the basic syntax for creating a std::pair:

#include <utility> // Required for std::pair using namespace std; pair<Type1, Type2> pairName;
  • Type1 and Type2 are the types of the first and second values in the pair.

  • pairName is the name of the std::pair object.

Common pair Functions

make_pair

Description: Creates a pair object with the given values.

Syntax:

pair<Type1, Type2> p = make_pair(value1, value2);

Example:

#include <iostream> #include <utility> using namespace std; int main() { auto p = make_pair(10, 'A'); // Creates a pair of int and char cout << "First: " << p.first << ", Second: " << p.second << endl; return 0; }

Default Constructor

Description: Creates a pair object with default-initialized members.

Syntax:

Example:


Parameterized Constructor

Description: Creates a std::pair object with specified values.

Syntax:

Example:


swap

Description: Swaps the contents of two std::pair objects.

Syntax:

Example:


tie

Description: Unpacks a pair into separate variables.

Syntax:

Example:

2024 - Programming 3 / Data Structures - Author: Dr. Kevin Roark