0
0
CppConceptBeginner · 3 min read

What is pair in C++: Simple Explanation and Example

pair in C++ is a simple container that holds exactly two values, possibly of different types, together as a single unit. It is useful when you want to group two related pieces of data without creating a full class or struct.
⚙️

How It Works

Think of pair as a small box with two compartments. Each compartment can hold one item, and these items can be of different types, like a number and a word. This lets you keep two related things together easily.

For example, if you want to store a person's age and name together, you can use a pair instead of making a whole new structure. The first item is called first and the second is called second. You can access them directly by these names.

💻

Example

This example shows how to create a pair holding an integer and a string, then print both values.

cpp
#include <iostream>
#include <utility> // for std::pair
#include <string>

int main() {
    std::pair<int, std::string> person;
    person.first = 30;           // age
    person.second = "Alice";   // name

    std::cout << "Age: " << person.first << ", Name: " << person.second << std::endl;
    return 0;
}
Output
Age: 30, Name: Alice
🎯

When to Use

Use pair when you need to group two related values quickly without extra setup. It is handy for returning two values from a function, storing key-value pairs, or working with simple data sets.

For example, pair is often used in maps where each key is paired with a value. It helps keep code clean and simple when you don't need a full class or struct.

Key Points

  • pair holds exactly two values, possibly of different types.
  • Access values using first and second.
  • Useful for simple grouping without creating new types.
  • Commonly used in standard library containers like std::map.

Key Takeaways

pair groups two related values of possibly different types in one object.
Access the two values using first and second members.
pair is great for simple data grouping without extra structures.
It is widely used in standard containers like std::map for key-value storage.