How do I construct and use std::pair in C++?

In C++, the `std::pair` is a simple container defined in the Standard Library that holds two values or objects. It is particularly useful when you want to return two related values from a function or store pairs of data.

To construct a `std::pair`, you can use its constructor or the `make_pair` function. Once you have a pair, you can access its elements using the `first` and `second` public members.

Example of Using std::pair

// Including the necessary header #include #include // for std::pair and std::make_pair using namespace std; int main() { // Creating a pair pair p1; // Default constructor p1.first = 1; // Assigning value to first p1.second = "Apple"; // Assigning value to second // Using make_pair to create a pair pair p2 = make_pair(2, "Banana"); // Accessing and displaying pair elements cout << "First pair: " << p1.first << ", " << p1.second << endl; cout << "Second pair: " << p2.first << ", " << p2.second << endl; return 0; }

std::pair C++ pair example C++ containers C++ programming make_pair